views:

268

answers:

3

For some reason the "".replace() method only replaces the first occurrence and not the others. Any ideas?

+3  A: 

You have to use the g modifier (for global) on 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.

Mayra
You may also need the "m" option for a multiline string.
Eric Wendelin
To make it more clear for the given problem: `str = str.replace (/\//g, "_");`
trinithis
Thanks guys! Life saver!
illuminatedtiger
Once your problem is solved, you should mark it as answered :)
Mayra
+1  A: 
str.replace(/\//g,”_”)
Charles Ma
+1  A: 
"Your/string".split("/").join("_")

if you don't require the power of RegExp

meouw