简体   繁体   中英

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?

Small correction: These are RegExp es, 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM