JavaScript .replace doesn't replace all occurr

2020-02-09 06:55发布

问题:

This question already has answers here:
Closed 7 years ago.

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

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

Firebug Screenshot:

回答1:

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.

So it should be:

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

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

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

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



回答2:

With a regular expression and flag g you got the expected result

"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



回答3:

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

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:

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