For some reason the "".replace()
method only replaces the first occurrence and not the others. Any ideas?
Asked
Active
Viewed 2.9k times
9

Paul D. Waite
- 96,640
- 56
- 199
- 270

illuminatedtiger
- 1,531
- 3
- 12
- 8
4 Answers
27
You have to use the g
modifier (for global) in your replace call.
str = str.replace(/searchString/g, "replaceWith")
In your particular case it would be:
str = str.replace (/\//g, "_");
Note that you must escape the /
in the regular expression.

Paul D. Waite
- 96,640
- 56
- 199
- 270

Cheryl Simon
- 46,552
- 15
- 93
- 82
-
You may also need the "m" option for a multiline string. – Eric Wendelin Jan 29 '10 at 01:15
-
2To make it more clear for the given problem: `str = str.replace (/\//g, "_");` – Thomas Eding Jan 29 '10 at 01:16
-
Once your problem is solved, you should mark it as answered :) – Cheryl Simon Jan 29 '10 at 01:35
-
@illuminatedtiger: No, really. You should mark it as answered. – Lightness Races in Orbit Jun 15 '11 at 16:52
7
str.replace(/\//g,”_”)

Charles Ma
- 47,141
- 22
- 87
- 101
-
Interesting that this answer contains the same Microsoft "smart quotes" as were originally in Mayra's answer. – Lightness Races in Orbit Jun 15 '11 at 16:53
-
0
Try this code:
text = text.replace(new RegExp("textToReplace","g"), "replacemntText"));

Arun Chandran Chackachattil
- 3,356
- 7
- 31
- 45

Owen
- 4,229
- 5
- 42
- 50