Javascript Replace With Global Not Working On Caret Symbol
i have following code for replacing var temp = '^hall^,^restaurant^'; temp.replace(/^/g, ''); console.log(temp); This does not Replace the ^ symbol from string. How can this n
Solution 1:
temp = temp.replace(/\^/g, '');
It is replacing once you escape the caret.
https://jsfiddle.net/ym7tt1L8/
And note that just writing temp.replace(/\^/g, '');
doesn't update your actual string. That is the reason you have to write
temp = temp.replace(/\^/g, '');
Solution 2:
In RegEx, the caret symbol is a recognized as a special character. It means the beginning of a string.
Additionally, replace returns the new value, it does not perform the operation in place, youneed to create a new variable.
For your case, you have to do one of the following:
var temp = "^hall^,^restaurant^";
var newString = temp.replace(/\^/g, ''); // Escape the caret
Or simply replace the character without using RegEx at all:
var temp = "^hall^,^restaurant^";
while (temp.indexOf('^') >= 0) {
temp = temp.replace('^', '');
}
Alternative version:
var temp = "^hall^,^restaurant^";
var newString = temp.split('^').join('');
Post a Comment for "Javascript Replace With Global Not Working On Caret Symbol"