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

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

Answers:

Answer

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.

Answer
"Your/string".split("/").join("_")

if you don't require the power of RegExp

Answer
str.replace(/\//g,”_”)
Answer

Try this code:

 text = text.replace(new RegExp("textToReplace","g"), "replacemntText")); 

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.