How do I replace all occurrences of "/" in a string with "_" in JavaScript?

javascript, replace

Solution

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.

Problem

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

Original source