Javascript Replace with Global not working on Caret Symbol

后端 未结 2 1583
情话喂你
情话喂你 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:52
     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, '');
    
    0 讨论(0)
  • 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('');
    
    0 讨论(0)
提交回复
热议问题