29

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
SeToY
  • 5,777
  • 12
  • 54
  • 94
  • old answers, today you probably want [replaceAll](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) – papo Apr 01 '21 at 06:21

3 Answers3

39

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.

raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • 8
    The "flags" parameter in your first example is non-standard, and won't work in Chrome or IE. – Jerod Venema Oct 04 '12 at 14:27
  • @jvenema Thank you, updated the answer mentioning that. Actually I never used strings in `.replace` first param when in need of global replace, so was a bit surprised when seeing that it's still possible to do without regex modifiers. ) – raina77ow Oct 04 '12 at 14:29
  • Thank you, this works... This is the most unintentional code I've ever come to see in my whole career :D – SeToY Oct 04 '12 at 14:30
  • 1
    It just saved my day... I was wondering what was happening... thanks ! – beluga Mar 27 '13 at 11:56
  • Firefox behaves like you have already passed /\./g as first parameter and replaces all instances. – Tanveer Badar May 19 '13 at 08:01
9

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

Luca Rainone
  • 16,138
  • 2
  • 38
  • 52
4

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,'')
Syllard
  • 49
  • 1