3

I realized that I couldn't match an empty regex with /(regex here)/ syntax, because // is a comment.

'this is a test'.match(//)
> SyntaxError: Unexpected token }

So, I tried new RegExp('') and it worked:

'this is a test'.match(new RegExp(''))
> [""]

But when I checked the output of new RegExp(''), it was this:

new RegExp('')
> /(?:)/

Why is this? (I am using Chrome version 26.0.1410.64 (Official Build 193017) m and this is in the JavaScript console)

tckmn
  • 57,719
  • 27
  • 114
  • 156
  • 1
    This is specified in the ECMA standard http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5. _"Regular expression literals may not be empty; instead of representing an empty regular expression literal, the characters // start a single-line comment. To specify an empty regular expression, use: /(?:)/."_ – elclanrs May 17 '13 at 01:34
  • @elclanrs Exactly, you should add that as an answer. – bfavaretto May 17 '13 at 01:36
  • Also, in [15.10.4.1](http://www.ecma-international.org/ecma-262/5.1/#sec-15.10.4.1) (which is about the RegExp constructor) the spec states: *If P is the empty String, this specification can be met by letting S be "(?:)".* – bfavaretto May 17 '13 at 01:37
  • @bfavaretto: I'll post all of this as answer. I missed section 15. – elclanrs May 17 '13 at 01:39

1 Answers1

3

This is specified in the ECMA standard in section 7.8.5:

Regular expression literals may not be empty; instead of representing an empty regular expression literal, the characters // start a single-line comment. To specify an empty regular expression, use: /(?:)/.

Also, in 15.10.4.1 the spec states:

If P is the empty String, this specification can be met by letting S be "(?:)".

elclanrs
  • 92,861
  • 21
  • 134
  • 171
  • Found a dup that looks exactly the same, LOL. http://stackoverflow.com/questions/6091974/in-javascript-does-an-empty-regex-pattern-have-defined-behavior – elclanrs May 17 '13 at 01:45