如何在 JavaScript 中用“_”替换字符串中所有出现的“/”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2159251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:00:55  来源:igfitidea点击:

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

javascriptreplace

提问by illuminatedtiger

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

出于某种原因,该"".replace()方法只替换第一次出现,而不替换其他。有任何想法吗?

回答by Cheryl Simon

You have to use the gmodifier (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.

请注意,您必须/在正则表达式中转义。

回答by meouw

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

if you don't require the power of RegExp

如果您不需要 RegExp 的功能

回答by Charles Ma

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

回答by Owen

Try this code:

试试这个代码:

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