JavaScript .replace 不会替换所有出现的

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

JavaScript .replace doesn't replace all occurrences

javascriptreplace

提问by SeToY

Possible Duplicate:
Javascript multiple replace
How do I replace all occurrences of "/" in a string with "_" in JavaScript?

可能的重复:
Javascript 多次替换
如何在 JavaScript 中用“_”替换字符串中所有出现的“/”?

In JavaScript, "11.111.11".replace(".", "")results in "11111.11". How can that be?

在 JavaScript 中,"11.111.11".replace(".", "")结果为"11111.11". 怎么可能?

Firebug Screenshot:
Firebug Screenshot

萤火虫截图:
萤火虫截图

回答by raina77ow

Quote from the doc:

来自文档的引用:

To perform a global search and replace, either include the g switch in the regular expression or if the first parameter is a string, include g in the flags parameter. Note:The flags argument does not work in v8 Core (Chrome and Node.js) and will be removed from Firefox.

要执行全局搜索和替换,请在正则表达式中包含 g 开关,或者如果第一个参数是字符串,则在 flags 参数中包含 g。注意:flags 参数在 v8 Core(Chrome 和 Node.js)中不起作用,将从 Firefox 中删除。

So it should be:

所以应该是:

"11.111.11".replace(/\./g, '');


This version (at the moment of edit) does work in Firefox...

此版本(在编辑时)在 Firefox 中确实有效...

"11.111.11".replace('.', '', 'g');

... but, as noted at the very MDN page, its support will be dropped soon.

...但是,正如 MDN 页面所指出的,它的支持很快就会被取消。

回答by Luca Rainone

With a regular expression and flag gyou got the expected result

使用正则表达式和标志,g您得到了预期的结果

"11.111.11".replace(/\./g, "")

it's IMPORTANT to use a regular expression because this:

使用正则表达式很重要,因为:

"11.111.11".replace('.', '', 'g'); // dont' use it!!

is not standard

不标准

回答by Syllard

First of all, replace() is a javascript function, and not a jquery function.

首先,replace() 是一个 javascript 函数,而不是一个 jquery 函数。

The above code replaces only the first occurrence of "." (not every occurrence). To replace every occurrence of a string in JavaScript, you must provide the replace() method a regular expression with a global modifier as the first parameter, like this:

上面的代码只替换了第一次出现的“.”。(并非每次都发生)。要替换 JavaScript 中出现的每个字符串,您必须为 replace() 方法提供一个正则表达式,并以全局修饰符作为第一个参数,如下所示:

"11.111.11".replace(/\./g,'')