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
Why does javascript replace only first instance when using replace?
提问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
回答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);
}

