开发者

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

开发者 https://www.devze.com 2022-12-18 05:33 出处:网络
For some reason the \"\".replace() method only replaces the first occurrence and not the oth开发者_开发百科ers. Any ideas?You have to use the g modifier (for global) in your replace call.

For some reason the "".replace() method only replaces the first occurrence and not the oth开发者_开发百科ers. 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("_")

if you don't require the power of RegExp


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


Try this code:

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

精彩评论

暂无评论...
验证码 换一张
取 消