javascript 得到“错误:无效的正则表达式”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31814535/
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
Getting "error: invalid regular expression"
提问by Ferus
So I have this code where I'd like to replace all single backslashes with 2 backslashes, for example: \ ---> \\ I tried to do this by the following code:
所以我有这段代码,我想用 2 个反斜杠替换所有单个反斜杠,例如:\ ---> \\ 我试图通过以下代码来做到这一点:
string = string.replace(new RegExp("\", "g"), "\\");
But apparently this doesn't work because I get the following error:
但显然这不起作用,因为我收到以下错误:
Uncaught SyntaxError: Invalid regular expression: //: \ at end of pattern
Uncaught SyntaxError: Invalid regular expression: //: \ at end of pattern
Any idea why?
知道为什么吗?
回答by CaldasGSM
The \
is a escape character for regular expressions, and also for javascript strings. This means that the javascript string "\\"
will produce the following content :\
. But that single \
is a escape character for the regex, and when the regex compiler finds it, he thinks: "nice, i have to escape the next character"... but, there is no next character. So the correct regex pattern should be \\
. That, when escaped in a javascript script is "\\\\"
.
该\
是一个转义字符正则表达式,也为JavaScript字符串。这意味着 javascript 字符串"\\"
将产生以下内容:\
. 但是那个单\
是正则表达式的转义字符,当正则表达式编译器找到它时,他想:“很好,我必须转义下一个字符”......但是,没有下一个字符。所以正确的正则表达式模式应该是\\
. 也就是说,当在 javascript 脚本中转义时是"\\\\"
.
So you should use:
所以你应该使用:
string = string.replace(new RegExp("\\", "g"), "\\");
as an alternative, and to avoid the javascript string escape, you can use a literal regex:
作为替代方案,为了避免 javascript 字符串转义,您可以使用文字正则表达式:
string = string.replace(/\/g, "\\");
回答by Lightness Races in Orbit
You escaped the backslash for JavaScript's string literal purposes, but you did not escape it for the regex engine's purposes. Remember, you are dealing with layers of technology here.
您出于 JavaScript 字符串文字的目的对反斜杠进行了转义,但并未出于正则表达式引擎的目的对其进行转义。请记住,您在这里处理的是技术层面。
So:
所以:
string = string.replace(new RegExp("\\", "g"), "\\");
Or, much better:
或者,更好:
string = string.replace(/\/g, "\\");