node.js string.replace 不起作用? [英] node.js string.replace doesn't work?
问题描述
var variableABC = "A B C";
variableABC.replace('B', 'D') //wanted output: 'A D C'
但是'variableABC'没有改变:
but 'variableABC' didn't change :
变量ABC = 'A B C'
variableABC = 'A B C'
当我希望它是A D C"时.
when I want it to be 'A D C'.
推荐答案
根据 Javascript 标准,String.replace
不应该修改字符串本身.它只返回修改后的字符串.您可以参考 Mozilla 开发者网络文档了解更多信息.
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')
上面给出的代码仅替换第一次出现.
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");
这篇关于node.js string.replace 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!