SyntaxStudy
Sign Up
JavaScript Advanced 5 min read

Regex Performance Tips

Regex Performance

Poorly written regex can backtrack catastrophically. Avoid ambiguous quantifiers on large inputs, compile regexes once if reused, and test with realistic data.

Example
// Compile once, use many times (avoid re-creating in loops)
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

function validateEmail(email) {
  return emailPattern.test(email);
}

// Catastrophic backtracking example to avoid:
// /^(a+)+$/ against "aaaaaaaaab" — exponential time

// Safer alternative using atomic groups or possessive quantifiers
// Not natively in JS — use workarounds or libraries

// Test with large strings in dev to catch slow patterns
Pro Tip

Avoid nested quantifiers like (a+)+ — they cause catastrophic backtracking on non-matching strings.