node.js string.replace 不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21162097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
node.js string.replace doesn't work?
提问by Aviram Netanel
var variableABC = "A B C";
variableABC.replace('B', 'D') //wanted output: 'A D C'
but 'variableABC' didn't change :
但 'variableABC' 没有改变:
variableABC = 'A B C'
变量ABC = 'ABC'
when I want it to be 'A D C'.
当我希望它是“AD C”时。
回答by Munim
According to the Javascript standard, String.replaceisn't supposed to modify the string itself. It just returns the modified string. You can refer to the Mozilla Developer Network documentationfor more info.
根据 Javascript 标准,String.replace不应修改字符串本身。它只返回修改后的字符串。您可以参考Mozilla 开发者网络文档了解更多信息。
You can always just set the string to the modified value:
您始终可以将字符串设置为修改后的值:
variableABC = variableABC.replace('B', 'D')
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");
回答by Jon
Isn't string.replace returninga value, rather than modifying the source string?
string.replace 不是返回一个值,而不是修改源字符串吗?
So if you wanted to modify variableABC, you'd need to do this:
所以如果你想修改 variableABC,你需要这样做:
var variableABC = "A B C";
variableABC = variableABC.replace('B', 'D') //output: 'A D C'
回答by Sriharsha
Strings are always modelled as immutable(atleast in heigher level languages python/java/javascript/Scala/Objective-C).
字符串总是被建模为不可变的(至少在高级语言 python/java/javascript/Scala/Objective-C 中)。
So any string operations like concatenation, replacements alwaysreturns a new string which contains intended value, whereas the original string will still be same.
因此,任何字符串操作(如连接、替换)总是返回一个包含预期值的新字符串,而原始字符串仍将相同。
回答by stackuser83
If you just want to clobber all of the instances of a substring out of a string without using regex you can using:
如果您只想在不使用正则表达式的情况下从字符串中删除子字符串的所有实例,您可以使用:
var replacestring = "A B B C D"
const oldstring = "B";
const newstring = "E";
while (replacestring.indexOf(oldstring) > -1) {
replacestring = replacestring.replace(oldstring, newstring);
}
//result: "A E E C D"

