Javascript 为什么javascript在使用替换时只替换第一个实例?

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

Why does javascript replace only first instance when using replace?

javascriptjquery

提问by chobo2

I have this

我有这个

 var date = $('#Date').val();

this get the value in the textbox what would look like this

这在文本框中获取值看起来像这样

12/31/2009

2009 年 12 月 31 日

Now I do this on it

现在我这样做

var id = 'c_' + date.replace("/", '');

and the result is

结果是

c_1231/2009

c_1231/2009

It misses the last '/' I don't understand why though.

它错过了最后一个 '/' 我不明白为什么。

回答by Gumbo

You need to set the gflagto replace globally:

您需要设置g标志以全局替换:

date.replace(new RegExp("/", "g"), '')
// or
date.replace(/\//g, '')

Otherwise only the first occurrence will be replaced.

否则只会替换第一次出现。

回答by bobince

Unlike the C#/.NET class library (and most other sensible languages), when you pass a Stringin as the string-to-match argument to the string.replacemethod, it doesn't do a string replace. It converts the string to a RegExpand does a regex substitution. As Gumbo explains, a regex substitution requires the g?lobal flag, which is not on by default, to replace all matches in one go.

与 C#/.NET 类库(以及大多数其他合理的语言)不同,当您将 aString作为字符串匹配参数传入该string.replace方法时,它不会执行字符串替换。它将字符串转换为 aRegExp并进行正则表达式替换。正如 Gumbo 解释的那样,正则表达式替换需要g?lobal 标志(默认情况下未启用)一次​​性替换所有匹配项。

If you want a real string-based replace?—?for example because the match-string is dynamic and might contain characters that have a special meaning in regexen?—?the JavaScript idiom for that is:

如果你想要一个真正的基于字符串的替换?—?例如因为匹配字符串是动态的并且可能包含在正则表达式中具有特殊含义的字符?—?JavaScript 习惯用法是:

var id= 'c_'+date.split('/').join('');

回答by HighTechProgramming15

You can use:

您可以使用:

String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
    return this.toString();
}
return this.split(search).join(replace);
}