4

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?

crashmstr
28.7k9 gold badges66 silver badges80 bronze badges
asked Oct 25, 2013 at 12:18
2
  • Why did you tag this performance? 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 :( Commented Oct 25, 2013 at 12:24

4 Answers 4

5

.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
Sign up to request clarification or add additional context in comments.

Comments

5

You can use replace with a regular expression :

"My New Report".replace(/ /g,'_')

Demo

answered Oct 25, 2013 at 12:22

Comments

4

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

Comments

2

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.

answered Oct 25, 2013 at 12:22

2 Comments

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('\\.', '_')
@Karl-AndréGagnon I have modified my answer with adding escaping replace string for regexp special characters.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.