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?
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?
Share Improve this question edited Oct 25, 2013 at 12:20 crashmstr 28.6k9 gold badges64 silver badges80 bronze badges asked Oct 25, 2013 at 12:18 IFrizyIFrizy 1,7454 gold badges18 silver badges33 bronze badges 2-
Why did you tag this
performance
? – crashmstr Commented Oct 25, 2013 at 12:19 - all answers below are correct, yet none of the authors care to upvote the other correct ones... that's a bit of a disappointment :( – Zathrus Writer Commented Oct 25, 2013 at 12:24
4 Answers
Reset to default 5.replace
will always replace the first occurence except if you use regular expression like that :
csvReport.name.replace(/ /g, "_");
You can use replace with a regular expression :
"My New Report".replace(/ /g,'_')
Demo
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, "_");
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.