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?
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.
window.location.replace
Commented
May 15, 2012 at 15:36
You need to escape the +
. +
has a special meaning in regEx.
var url = window.location.href.replace(/\+/g, ' ');
Edit: Changed to .href
+
is a quantifier in regEx which means it will test for any character before +
for 1 or more occurrences.
Commented
May 15, 2012 at 15:38
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.
+
is a special regex characters.