如何在 JavaScript 中对字符串中的反斜杠进行全局替换

发布于 2024-11-04 07:42:46 字数 321 浏览 0 评论 0原文

我已经尝试过:(如果所有斜杠都难以阅读,第一行应替换正斜杠,第二行应替换反斜杠,第三行应替换星号。

newbigbend = bb_val.replace(/\//gi,"");
newbigbend = bb_val.replace(/\\/gi,"");
newbigbend = bb_val.replace(/*/gi,"");

替换所有正斜杠,反斜杠和星号。但是当浏览器获取到中间行 newbigbend = bb_val.replace(/\\/gi,""); 它认为它是一个未终止的注释。我知道使用转义来替换正斜杠。 。

I've tried: (Incase all the slashes make it hard to read, 1st line should replace forward slashes, 2nd line should replace backslashes, 3rd line should replace asterisks.

newbigbend = bb_val.replace(/\//gi,"");
newbigbend = bb_val.replace(/\\/gi,"");
newbigbend = bb_val.replace(/*/gi,"");

to replace all forward slashes, backslashes and asterisks. But when the browser gets to the middle line newbigbend = bb_val.replace(/\\/gi,""); it thinks its an unterminated comment. I know to use the escape to replace the forward slash. Not sure about back.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

海拔太高太耀眼 2024-11-11 07:42:46

安德鲁·库珀的就为什么第三个陈述出错而言,答案是正确的。但您每次也会覆盖 newbigbend,因此您根本看不到前两次替换的结果。

如果您尝试将所有斜杠、反斜杠和星号替换为空,请执行以下操作:

newbigbend = bb_val.replace(/[/\\*]/g, "");

请注意,您不需要 i 标志,这些字符都不区分大小写。 (请注意,在 [] 中,您不需要转义 /*,因为它们在那里没有特殊含义.) 实例

但是,如果您出于某种原因希望将其作为三个单独的语句,请在后两个语句中使用 newbigbend (并添加 Andrew 标记的反斜杠):

newbigbend = bb_val.replace(/\//gi,"");
newbigbend = newbigbend.replace(/\\/gi,"");
newbigbend = newbigbend.replace(/\*/gi,"");

Andrew Cooper's answer is correct in terms of why that third statement is going wrong. But you're also overwriting newbigbend each time, so you won't see the result of the first two replacements at all.

If you're trying to replace all slashes, backslashes, and asterisks with nothing, do this:

newbigbend = bb_val.replace(/[/\\*]/g, "");

Note you don't need the i flag, none of those characters is case sensitive anyway. (And note that within the [], you don't need to escape / or *, because they don't have special meaning there.) Live example.

But if you want it as three individual statements for whatever reason, then use newbigbend in the second two (and add the backslash Andrew flagged up):

newbigbend = bb_val.replace(/\//gi,"");
newbigbend = newbigbend.replace(/\\/gi,"");
newbigbend = newbigbend.replace(/\*/gi,"");
ま柒月 2024-11-11 07:42:46

您还需要转义 *

newbigbend = bb_val.replace(/\*/gi,"");

You also need to escape the *

newbigbend = bb_val.replace(/\*/gi,"");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文