When a regex engine backtracks through exponentially many possible matches, a seemingly ordinary input can consume excessive execution time and block JavaScript’s thread. Exploiting this behavior to overwhelm a system is called ReDoS. section 12.6.3
Listing 12.13 A regex with catastrophic backtracking
const rosterRegex = /^(?:\w+\s*)+$/; #A
console.assert( #B
rosterRegex.test("Hattori Yoshi Fuma"), #B
"A genuine roster is accepted instantly", #B
); #B
const attack = #C
"I will erase your existence from this realm!"; #C
const start = performance.now(); #C
rosterRegex.test(attack); #C
const elapsed = performance.now() - start; #C
console.log(
`Rejecting the attack string took ${elapsed.toFixed(0)}ms`,
);
The pattern /^(?:\w+\s*)+$/ accepts a roster, but a near-match ending in ! makes the engine reconsider how it split the words. With 36 letters, the example describes 2³⁶ possible splits. section 12.6.3
Options for reducing the risk include:
- Consider a DFA-based engine, such as node-re2; it avoids backtracking and guarantees linear execution time, but does not support backreferences or lookbehind. section 12.6.3

