Amir
Amir

Reputation: 4151

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.

Upvotes: 7

Views: 139

Answers (3)

pimvdb
pimvdb

Reputation: 154868

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.

Upvotes: 3

Wayne
Wayne

Reputation: 60414

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

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

Evaluates to:

["/"]

Upvotes: 3

Paul
Paul

Reputation: 141837

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.

Upvotes: 3

Related Questions