[英]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. 由于某种原因, "".replace()
方法仅替换第一次出现而不替换其他出现。 Any ideas? 有任何想法吗?
You have to use the g
modifier (for global) in your replace call. 您必须在替换调用中使用g
修饰符(用于全局)。
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"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.