JavaScript Regular Expressions Cheat Sheet & Pitfalls
Practical reference for anchors, character classes, lookarounds, named capture groups, flags, and avoiding catastrophic backtracking.
Updated 2026-11-28
Essential tokens and anchors
Use `^` and `$` when validating whole strings rather than searching substrings. Prefer explicit character classes like `[^\s]+` over greedy `.*`, and use `(?:...)` non-capturing groups when you do not need backreferences.
Named capture groups and replacement
Write `(?<name>pattern)` to name a capture group and reference it as `$<name>` in `String.prototype.replace` or inspect `match.groups.name`.
Preventing catastrophic backtracking (ReDoS)
Nested quantifiers such as `(a+)+` or overlapping alternations `(a|aa)+` can trigger exponential runtime on non-matching input. Keep quantifiers unambiguous, bound input length, and test edge cases in a Web Worker-protected tester.