node.js string.replace doesn't work?

前端 未结 4 1848
庸人自扰
庸人自扰 2021-02-02 05:12
var variableABC = \"A B C\"; 
variableABC.replace(\'B\', \'D\') //wanted output: \'A D C\'

but \'variableABC\' didn\'t change :

4条回答
  •  遥遥无期
    2021-02-02 05:57

    According to the Javascript standard, String.replace isn't supposed to modify the string itself. It just returns the modified string. You can refer to the Mozilla Developer Network documentation for more info.

    You can always just set the string to the modified value:

    variableABC = variableABC.replace('B', 'D')

    Edit: The code given above is to only replace the first occurrence.

    To replace all occurrences, you could do:

     variableABC = variableABC.replace(/B/g, "D");  
    

    To replace all occurrences and ignore casing

     variableABC = variableABC.replace(/B/gi, "D");  
    

提交回复
热议问题