JavaScript字符串替换的行为

JavaScript字符串替换的行为,javascript,replace,Javascript,Replace,为什么replace函数不替换所有出现的情况 1)不起作用的示例: //the funcion call '999.999.999,00'.replace('.', '') //This replaces only the first match, given as result as below '999999.999,00' //the funcion call '999.999.999,00'.replace(/\./g, '') //This replaces all match

为什么
replace
函数不替换所有出现的情况

1)不起作用的示例:

//the funcion call
'999.999.999,00'.replace('.', '')

//This replaces only the first match, given as result as below
'999999.999,00'
 //the funcion call
'999.999.999,00'.replace(/\./g, '')

//This replaces all matches, given as result as below
'999999999,00'
2)使用正则表达式但有效的Ex:

//the funcion call
'999.999.999,00'.replace('.', '')

//This replaces only the first match, given as result as below
'999999.999,00'
 //the funcion call
'999.999.999,00'.replace(/\./g, '')

//This replaces all matches, given as result as below
'999999999,00'

Ex 1是否正确?
replace
是否正确?

在第一种情况下,您应该将标志作为第三个参数传递:

'999.999.999,00'.replace('.', '', 'g')

更多信息,请访问。但是,并非所有浏览器都支持此功能,您应自行承担使用此功能的风险。

是。JavaScript替换应该只替换第一个匹配项。如果要替换同一字符串的多个字符串,则确实应该使用正则表达式。您还可以使用一个简单的while循环:

var match = '.';
var str = '999.999.999,00';
while(str.indexOf(match) != -1) str = str.replace(match, '');

但通常只使用正则表达式要容易得多。对于需要对大块文本执行的简单替换操作,这可能是相关的。对于较小的替换操作,使用Regex就可以了。

这是预期的行为。这就是它的工作原理,请查看文档。稍微阅读一下替换可以回答您的问题question@Huangism我给stackoverflow带来的只是我不能完全理解的东西,即使是在读了博士论文之后!谢谢你的帮助!我在回答中包含了一个指向a的链接,我提到的while循环比正则表达式更快。并非所有浏览器都支持第三个参数。它在Chrome中不起作用。最好使用正则表达式。@RocketHazmat你是对的。更新了我的答案。