2

I have a URL that I need to manipulate. I cant seem to replace all the '+' within a query string with whitespace.

var url = window.location.replace(/+/g, ' ');

What am I doing wrong here?

Or is there a better method?

2
  • 2
    + is a special regex characters. Commented May 15, 2012 at 15:33
  • Plus is a special regex character. Escape it. Commented May 15, 2012 at 15:33

3 Answers 3

4

replace() is a method on window.location, but it's not the one you think. You want call replace() on location.href.

var url = window.location.href.replace(/\+/g, ' ');

As Vega answered, note that you also need to escape the + because of its special meaning as a quantifier.

Sign up to request clarification or add additional context in comments.

1 Comment

replace won't replace all occurrences, but +1 for window.location.replace
3

You need to escape the +. + has a special meaning in regEx.

var url = window.location.href.replace(/\+/g, ' ');

Edit: Changed to .href

4 Comments

this is perfect, why does it have a different meaning if you mind me asking?
@CecilTheodore because it's part of the regex syntax.
@CecilTheodore: It's quantifier. It means "match the preceding pattern one or more times". I recommend to have a look at regular-expressions.info.
+ is a quantifier in regEx which means it will test for any character before + for 1 or more occurrences.
0

There is an alternative if you don't need to run it thousands of times.

var url = window.location.href.split('+').join(' ');

The reason I mentioned how often it is run is this will be a little slower than a regex in Firefox, a fair bit slower in chrome and oddly faster in Opera according to the tests here: http://jsperf.com/regex-vs-split-join

So for a simple URL change it should be fine to use that syntax.

Comments

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.