简体   繁体   中英

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?

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.

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

如果你不需要RegExp的强大功能

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

试试这段代码:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM