Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why /}/ is a valid regular expression in javascript?

/}/ is a valid regular expression in JS:

alert('}}}'.replace(/}/g, "!"))

However, the ECMA standard doesn't seem to allow that:

PatternCharacter ::SourceCharacter but not any of:
      ^ $ \ . * + ? ( ) [ ] { } |

Why does the above work? Is this feature universally supported? Is it documented anywhere?

like image 837
georg Avatar asked Oct 06 '22 06:10

georg


2 Answers

Small correction: These are RegExpes, which are different from pure Regular Expressions.

Why does the above work?

Because the JS implementation you're using does not strictly conform to the ES5 standard, which states that it should raise a SyntaxError. As Bergi commented, this is described in $15.10.4.1.

Is this feature universally supported?

No. It should never be considered universally supported if it's not in the standard.

Is it documented anywhere?

Probably not, it's just an artifact of undefined behavior. Look to the documentation of whatever JS engine you tested on.

like image 154
Deestan Avatar answered Oct 22 '22 14:10

Deestan


http://www.regular-expressions.info/characters.html :

Most regular expression flavors treat the brace { as a literal character, unless it is part of a repetition operator like {1,3}. So you generally do not need to escape it with a backslash, though you can do so if you want. An exception to this rule is the java.util.regex package: it requires all literal braces to be escaped.

Seems that javascript is not an exception.

like image 31
xdazz Avatar answered Oct 22 '22 16:10

xdazz