Regex can be slow — learn how to avoid catastrophic backtracking, optimize your patterns, and use the right tools for the job.
A poorly written regex can take exponential time to fail on a non-matching input. This is known as ReDoS (Regular Expression Denial of Service), and it's been responsible for outages at Cloudflare and Stack Overflow.
/^(a+)+$/
On input aaaaaaaaaaaab, the engine tries every possible grouping before concluding no match. The patterns (X+)+, (X|X)+, and (X+)* are red flags.
// Can take seconds or cause a timeout:
/^(a+)+$/.test("aaaaaaaaaaaaaaaaaab");
1. Be specific — avoid over-using .*
// Slow
/<.*>/
// Fast — negated class
/<[^>]*>/
2. Anchor when possible
// Scans the whole string
/\d+/
// Anchored — stops early
/^\d+$/
3. Use non-capturing groups
// Capturing group (slower)
/(\d+)/
// Non-capturing group (faster)
/(?:\d+)/
4. Most likely alternatives first
/\.(?:jpg|png|gif|webp)$/i
JSON.parse()Test your patterns safely with the Regex Tester.