A quantifier tells a regular expression how many times the preceding term may occur. Use one when a fixed literal is too restrictive—for example, when a word may begin with one `t` or several. section 12.2.2
Choose the repetition count the pattern should allow:
- `+` means one or more: `/^t+est$/` matches `test` and `ttest`, but not `est`. section 12.2.2
- `*` means zero or more: `/^t*est$/` also matches `est`. section 12.2.2
- `{4}` specifies exactly four repetitions; `{4,10}` permits four through ten; `{4,}` permits four or more. section 12.2.2
Greedy versus nongreedy
Quantifiers are greedy by default: they consume as much matching text as possible. Applied to `<Ninjas><Unite!>`, `/<.*>/` matches the whole string. Add `?` after the repetition operator—`/<.*?>/`—to consume only enough for a match, yielding `<Ninjas>`. This illustrates matching behavior, not a strategy for parsing real HTML; use an HTML parser for that. section 12.2.2
A quantifier can also repeat a group. In `/^(?:\w+\s*)+$/`, the outer `+` repeats a sequence of word characters and optional whitespace. The pattern accepts a space-separated roster, but a trailing `!` makes the end anchor fail. The regex then backtracks through alternative ways to divide the words. Because `\s*` may match nothing, rejecting that input can require exponentially many possibilities. Repetition is therefore also a performance consideration, particularly when a match fails. 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`,
);
Run the timed JavaScript example to compare an accepted roster with a rejected string that triggers catastrophic backtracking. section 12.6.3



