Reputation: 681
I have a Regular Expression: [a-z]{
which is a valid expression as per Javascript's
RegExp
.
But if i change it to: [a-z](
It's not a valid expression. I need to escape "("
to make it work.
Why does the "{"
without escaping works?
Is there a way to force Javascript to return it as invalid expression?
Upvotes: 1
Views: 62
Reputation: 371193
An unmatched {
is permitted and interpreted as a literal {
to match because that's what the specification requires. (It can't be changed, because if it was, existing websites would break, and the specification supports backwards compatibility over everything else).
But, in newer environments, you can add the u
unicode flag, which adds extra requirements and turns plain {
s, which are likely mistakes, into errors:
const re = /foo{/u;
Uncaught SyntaxError: Invalid regular expression: /foo{/: Incomplete quantifier @ JS line 1
(There are various other behaviors that adding the u
flag does, but they're likely not relevant for most use-cases)
Upvotes: 4