I have next code in javascript:
csvReport.name = "My New Report";
$scope.filename = csvReport.name.replace(" ", "_");
But I get $scope.filename = My_New Report. Not all spaces replacing.
What is it?
4 Answers 4
.replace will always replace the first occurence except if you use regular expression like that :
csvReport.name.replace(/ /g, "_");
answered Oct 25, 2013 at 12:22
Karl-André Gagnon
33.9k5 gold badges53 silver badges77 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
answered Oct 25, 2013 at 12:22
Satpal
134k13 gold badges168 silver badges171 bronze badges
Comments
You can use regular expression with a global switch (g) to actually replace all instances, like this:
csvReport.name = "My New Report";
$scope.filename = csvReport.name.replace(/ /g, "_");
answered Oct 25, 2013 at 12:22
Zathrus Writer
4,3315 gold badges30 silver badges53 bronze badges
Comments
Function replace only replace first appearance of first argument. You can use regular expression to replace in whole string.
Try this:
if (!String.replaceAll) {
String.prototype.replaceAll = function(replace, value) {
var regexpStr = replace.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")
return this.replace(new RegExp(regExpStr, 'g'), value);
};
}
This way you have additional function that works on whole string.
2 Comments
Karl-André Gagnon
This work for the space, but it is dangerous if he want to replace character like
. since . mean every character in regExp. However you can escape in your function with a regexp. Or escape it when calling the function : .replaceAll('\\.', '_')maketest
@Karl-AndréGagnon I have modified my answer with adding escaping
replace string for regexp special characters.lang-js
performance?