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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5854352/
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-10-25 18:34:56  来源:igfitidea点击:

How to do a global replace on backslash in a string in javascript

javascripthtmlreplace

提问by Mike Felder

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.

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

回答by T.J. Crowder

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

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

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 iflag, 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.

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

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

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

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

回答by Andrew Cooper

You also need to escape the *

你还需要逃避 *

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