Skip to content

Invalid Regular Expression

Quick summary

You passed a malformed pattern to RegExp() — the engine rejects it with a SyntaxError before any matching can happen.

Why this happens

  • Unbalanced parentheses or brackets inside the pattern (e.g., (a with no closing ))

  • Invalid quantifier such as * or + applied to nothing, or a quantifier nested incorrectly

  • Trailing backslash that escapes the end of the string instead of a character

Minimal example

✗ Broken code
const re = new RegExp("(a+b"); // SyntaxError: Unterminated group
console.log(re.test("aab"));
✓ Fixed code
const re = new RegExp("(a+b)"); // balanced group
console.log(re.test("aab")); // true

The pattern (a+b is missing its closing parenthesis, so the regex engine cannot compile it. Adding ) balances the group and the pattern compiles successfully.

How to diagnose

  • Read the SyntaxError message — it usually points to the position of the bad token

  • Test the pattern in a regex tester (regex101.com) to isolate the malformed segment

  • Print the pattern string to confirm it is what you intended after escaping

How to fix

  • Balance every opening group with a closing parenthesis or bracket

  • Remove or correct misplaced quantifiers and escape literal special characters with a backslash

  • Build dynamic patterns with String.raw or careful double-escaping to avoid losing backslashes

How to prevent

  • Validate user-supplied patterns in a try/catch before compiling them

  • Use a linter or regex tester while authoring complex patterns

Related Resources

Related Glossary

Related Lessons

  • Strings

    Learn about strings and pattern matching.

← Back to language