For some reason the "".replace() method only replaces the first occurrence and not the others. Any ideas?
Asked
Active
Viewed 2.5k times
9
Paul D. Waite
- 93,468
- 54
- 192
- 264
illuminatedtiger
- 1,431
- 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
- 93,468
- 54
- 192
- 264
Cheryl Simon
- 45,901
- 15
- 92
- 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
- 44,439
- 22
- 83
- 99
-
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,336
- 7
- 30
- 44
Owen
- 3,989
- 5
- 41
- 49