Regex Performance
Poorly written regex can backtrack catastrophically. Avoid ambiguous quantifiers on large inputs, compile regexes once if reused, and test with realistic data.
Poorly written regex can backtrack catastrophically. Avoid ambiguous quantifiers on large inputs, compile regexes once if reused, and test with realistic data.
// 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
Avoid nested quantifiers like (a+)+ — they cause catastrophic backtracking on non-matching strings.
More in JavaScript