1

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?

2
  • this may help javascript.info/regexp-escaping Commented May 27, 2020 at 14:12
  • 2
    Because it was implemented that way. I don't think the actual reason for this is very relevant here. Why do you need the first regex to be invalid? Commented May 27, 2020 at 14:14

1 Answer 1

4

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.