I'm trying to replace multiple carets (^) in a string with spaces in Javascript. Following the w3schools entry on replace(), I used this code:
var str = "Salt^Lake^City, UT";
var result = str.replace(/^/g, " ");
However, value of result
is " Salt^Lake^City, UT". One caret is replaced when I run this code:
var result = str.replace("^", " ");
but I want to replace all of an arbitrary number of carets. Is there something obvious I'm missing about globally replacing in Javascript? I could write a function using str.replace("^", " ");
to remove all the carets, but I'd rather use the built-in global replace.
I'm trying to replace multiple carets (^) in a string with spaces in Javascript. Following the w3schools entry on replace(), I used this code:
var str = "Salt^Lake^City, UT";
var result = str.replace(/^/g, " ");
However, value of result
is " Salt^Lake^City, UT". One caret is replaced when I run this code:
var result = str.replace("^", " ");
but I want to replace all of an arbitrary number of carets. Is there something obvious I'm missing about globally replacing in Javascript? I could write a function using str.replace("^", " ");
to remove all the carets, but I'd rather use the built-in global replace.
- Don't consult w3schools. Some information on that webpage is wrong (see this for an explanation: w3fools.) – Max Leske Commented Mar 13, 2013 at 17:55
2 Answers
Reset to default 8The ^
character matches the start of the string in a regex, so you need to escape it so it will be treated as a literal character. That is why in your example, the result string has a new space added at the start of the string.
var result = str.replace(/\^/g, " ");
You can also use another handy way which is roundabout.
var result = str.split('^').join(' ') ;