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 not work?

Answers:

Answer
 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, '');
Answer

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('');

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.