是“\/”在 javascript 正则表达式中有效吗?
以下代码有效吗?
function test() {
return /\//.exec("\/");
}
alert(test());
似乎许多 javascript 压缩器(包括 http://jscompress.com/ 上的 jsmin)都考虑了“//”第二行是评论的开始。我认为这是“平凡”实现的缩小器中的一个错误,因为我尝试的所有浏览器实现都可以毫无问题地运行它。 在 jsfiddle 上尝试。
Is the following code valid?
function test() {
return /\//.exec("\/");
}
alert(test());
It seems that many javascript minifiers (including jsmin at http://jscompress.com/) consider the "//" on the second line to be the start of a comment. I assume it's a bug in the "trivially" implemented minifiers, since all the browser implementations I tried run it without a problem. Try it on jsfiddle.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我有兴趣在规范中查找它,根据它它是有效的:
\/
被认为是RegularExpressionBackslashSequence
,因此是RegularExpressionBody 的一部分
,因此不能成为//
注释标记的一部分。I was interested in looking it up in the specs, and according to it it is valid:
The
\/
is considered aRegularExpressionBackslashSequence
, and hence is part ofRegularExpressionBody
, and as a result cannot be part of the//
comment marker.是的,这是有效的 javascript :) 这是压缩器中的一个错误,可能应该被修复。如果您愿意,您可以通过让正则表达式在其末尾添加一些愚蠢的内容来绕过它,例如:
基本上就是说,要么是字符串的结尾,要么不是字符串的结尾,而不捕获。但我认为这不是一个好的解决方案,我自己也不会使用它哈哈。
Yes, that is valid javascript :) That is a bug in the minifier, and should probably be fixed. You could get around it if you wanted by making your regex have something stupid at the end of it like:
Which basically says, either the end of the string, or not the end of the string, without capturing. But I don't think that's a good solution and I wouldn't use it myself haha.
是的,这是合法的。
\/
匹配文字/
。第一个\
对/
进行转义。该行:评估为:
Yes, this is legal.
\/
matches a literal/
. The first\
escapes the/
. The line:Evaluates to: