Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript .replace doesn't replace all occurrences [duplicate]

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:
Firebug Screenshot

like image 851
SeToY Avatar asked Oct 04 '12 14:10

SeToY


3 Answers

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.

like image 200
raina77ow Avatar answered Nov 09 '22 04:11

raina77ow


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

like image 37
Luca Rainone Avatar answered Nov 09 '22 05:11

Luca Rainone


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,'')
like image 30
Syllard Avatar answered Nov 09 '22 04:11

Syllard