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?

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, "_");
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

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, "_");

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.

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

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.