Javascript 替换() 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13549413/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:20:14  来源:igfitidea点击:

Javascript replace() function

javascriptreplace

提问by mseifert

This is a simple replace() question - and I can't get it working to replace a substring in the function below.

这是一个简单的 replace() 问题 - 我无法在下面的函数中替换子字符串。

function linkOnClick(){
    var anyNameYouLike = 'some sort of text/string right here';
    anyNameYouLike.replace('right','in');
    alert(anyNameYouLike)
}

It should return "some sort of text/string in here" but doesn't. What am I doing wrong? I'm fairly new with Javascript (if it isn't obvious...)

它应该返回“这里有某种文本/字符串”,但没有。我究竟做错了什么?我对 Javascript 还很陌生(如果不明显的话......)

回答by Juvanis

anyNameYouLike = anyNameYouLike.replace('right','in');

回答by jfriend00

In javascript, strings are immutable (they are never modified). As such, the .replace()function does not modify the string you call it on. Instead, it returns a new string. So, if you want anyNameYouLiketo contain the modified string, you have to assign the result to it like this:

在 javascript 中,字符串是不可变的(它们永远不会被修改)。因此,该.replace()函数不会修改您调用它的字符串。相反,它返回一个新字符串。所以,如果你想anyNameYouLike包含修改后的字符串,你必须像这样将结果分配给它:

anyNameYouLike = anyNameYouLike.replace('right','in');

For more info, refer to the MDN description of the .replace()methodwhich says this:

有关更多信息,请参阅.replace()方法MDN 描述,其中说明:

Returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.

返回一个新字符串,其中部分或全部模式匹配项被替换项替换。模式可以是字符串或正则表达式,替换可以是字符串或每次匹配时调用的函数。

And, in the description of the .replace()method, it says this:

并且,在.replace()方法的描述中,它是这样说的:

This method does not change the String object it is called on. It simply returns a new string.

此方法不会更改调用它的 String 对象。它只是返回一个新字符串。