如何替换所有出现的“/"?在带有“_"的字符串中在 JavaScript 中? [英] How do I replace all occurrences of "/" in a string with "_" in JavaScript?

查看:10
本文介绍了如何替换所有出现的“/"?在带有“_"的字符串中在 JavaScript 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,"".replace() 方法仅替换第一次出现的位置,而不替换其他位置.有什么想法吗?

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

推荐答案

您必须在替换调用中使用 g 修饰符(用于全局).

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.

这篇关于如何替换所有出现的“/"?在带有“_"的字符串中在 JavaScript 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆