Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "\/" valid inside a javascript regex?

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.

like image 295
Amir Avatar asked Jul 21 '11 21:07

Amir


3 Answers

I was interested in looking it up in the specs, and according to it it is valid:

RegularExpressionLiteral ::
    / RegularExpressionBody / RegularExpressionFlags
RegularExpressionBody ::
    RegularExpressionFirstChar RegularExpressionChars
RegularExpressionChars ::
    [empty]
    RegularExpressionChars RegularExpressionChar
RegularExpressionFirstChar ::
    RegularExpressionNonTerminator but not * or \ or / or [
    RegularExpressionBackslashSequence
    RegularExpressionClass
RegularExpressionChar ::
    RegularExpressionNonTerminator but not \ or / or [
    RegularExpressionBackslashSequence
    RegularExpressionClass
RegularExpressionBackslashSequence ::
    \ RegularExpressionNonTerminator
RegularExpressionNonTerminator ::
    SourceCharacter but not LineTerminator

The \/ is considered a RegularExpressionBackslashSequence, and hence is part of RegularExpressionBody, and as a result cannot be part of the // comment marker.

like image 67
pimvdb Avatar answered Nov 03 '22 19:11

pimvdb


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:

return /\/(?:.|$)/.exec("\/");

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.

like image 3
Paul Avatar answered Nov 03 '22 18:11

Paul


Yes, this is legal. \/ matches a literal /. The first \ escapes the /. The line:

/\//.exec("\/");

Evaluates to:

["/"]
like image 3
Wayne Avatar answered Nov 03 '22 18:11

Wayne