9

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

Paul D. Waite
  • 93,468
  • 54
  • 192
  • 264
illuminatedtiger
  • 1,431
  • 3
  • 12
  • 8

4 Answers4

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
9
"Your/string".split("/").join("_")

if you don't require the power of RegExp

meouw
  • 41,026
  • 10
  • 50
  • 68
7
str.replace(/\//g,”_”)
Charles Ma
  • 44,439
  • 22
  • 83
  • 99
0

Try this code:

 text = text.replace(new RegExp("textToReplace","g"), "replacemntText")); 
Owen
  • 3,989
  • 5
  • 41
  • 49