Greedy vs Lazy Quantifiers
What you'll learn: How quantifiers grab as much as possible by default, and how to make them take only what they need.
The Default: Greedy Behavior
By default, all quantifiers (*, +, ?, {n,m}) are greedy—they match as many characters as possible while still allowing the overall pattern to succeed. Think of them as hungry: they'll eat everything on the plate before checking if they should have saved some for later.
const text = '<div>Hello</div><div>World</div>';
const greedy = /<div>.*<\/div>/;
console.log(text.match(greedy)[0]);
// '<div>Hello</div><div>World</div>'
// Matches from the FIRST <div> to the LAST </div>
The .* grabbed everything between the first opening tag and the last closing tag, not stopping at the first </div> it encountered.
Making Quantifiers Lazy
Add a ? after any quantifier to make 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 = '<div>Hello</div><div>World</div>';
const lazy = /<div>.*?<\/div>/;
console.log(text.match(lazy)[0]);
// '<div>Hello</div>'
// Matches only the FIRST complete <div>...</div>
Now .*? stops as soon as it finds the first </div>, matching the smallest possible string.
When to Use Each
- Greedy: When you want to capture the maximum stretch (e.g., everything between outer delimiters)
- Lazy: When you want to stop at the earliest match (e.g., individual HTML tags, quoted strings)
Key Takeaway: Quantifiers are greedy by default, matching as much as possible. Add ? after a quantifier (*?, +?, ??, {n,m}?) to make it lazy and match as little as possible.