如何在 JavaScript 中对字符串中的反斜杠进行全局替换
我已经尝试过:(如果所有斜杠都难以阅读,第一行应替换正斜杠,第二行应替换反斜杠,第三行应替换星号。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
安德鲁·库珀的就为什么第三个陈述出错而言,答案是正确的。但您每次也会覆盖
newbigbend
,因此您根本看不到前两次替换的结果。如果您尝试将所有斜杠、反斜杠和星号替换为空,请执行以下操作:
请注意,您不需要
i
标志,这些字符都不区分大小写。 (请注意,在[]
中,您不需要转义/
或*
,因为它们在那里没有特殊含义.) 实例。但是,如果您出于某种原因希望将其作为三个单独的语句,请在后两个语句中使用 newbigbend (并添加 Andrew 标记的反斜杠):
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:
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):您还需要转义
*
You also need to escape the
*