Greedy vs Lazy Quantifiers
You'll learn: How to control whether quantifiers capture the maximum or minimum amount of text.
The Greedy Default
By default, all quantifiers in JavaScript regular expressions are greedy—they match as many characters as possible while still allowing the overall pattern to succeed. This can cause unexpected results when you're trying to extract specific parts of a string.
Consider matching text between quotes:
const text = 'He said "hello" and then "goodbye"';
const greedy = /".*"/;
console.log(text.match(greedy)[0]);
// Output: "hello" and then "goodbye"
The .* consumed everything from the first " to the last ", not stopping at the first closing quote.
Making Quantifiers Lazy
Adding a ? immediately after a quantifier makes it lazy (also called "non-greedy" or "reluctant"). A lazy quantifier matches as few characters as possible while still allowing the pattern to succeed.
const text = 'He said "hello" and then "goodbye"';
const lazy = /".*?"/;
console.log(text.match(lazy)[0]);
// Output: "hello"
Now .*? stops at the first closing quote it encounters.
Think of It Like Eating
- Greedy (
*,+,{n,}): "I'll eat everything on the table until I'm forced to stop." - Lazy (
*?,+?,{n,}?): "I'll eat just enough to satisfy the pattern and no more."
When to Use Which
Use lazy quantifiers when you want to match the shortest possible string between delimiters or boundaries. Use greedy when you genuinely want the longest match.
Key Takeaway: Greedy quantifiers maximize their match; adding ? after a quantifier makes it lazy, matching the minimum needed to satisfy the pattern.