Javascript Replace with Global not working on Caret Symbol

后端 未结 2 1613
情话喂你
情话喂你 2021-01-24 01:22

i have following code for replacing

 var temp =  \"^hall^,^restaurant^\";
 temp.replace(/^/g, \'\');
 console.log(temp);

This does not Replace

2条回答
  •  情书的邮戳
    2021-01-24 01:57

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

提交回复
热议问题