9

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

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
illuminatedtiger
  • 1,531
  • 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
  • 96,640
  • 56
  • 199
  • 270
Cheryl Simon
  • 46,552
  • 15
  • 93
  • 82
9
"Your/string".split("/").join("_")

if you don't require the power of RegExp

meouw
  • 41,754
  • 10
  • 52
  • 69
7
str.replace(/\//g,”_”)
Charles Ma
  • 47,141
  • 22
  • 87
  • 101
0

Try this code:

 text = text.replace(new RegExp("textToReplace","g"), "replacemntText")); 
Owen
  • 4,229
  • 5
  • 42
  • 50