Quantifiers: Controlling Repetition
Quantifiers specify how many times the preceding element must appear in the string for a match to succeed.
1. Core Quantifiers
| Quantifier | Meaning | Example Pattern | Matches |
* | Zero or more times | ab*c | ac, abc, abbc |
+ | One or more times | ab+c | abc, abbc (not ac) |
? | Zero or one time | colou?r | color, colour |
{n} | Exactly n times | \d{4} | 2026 |
{n,m} | Between n and m times | \d{2,4} | 12, 123, 1234 |
{n,} | At least n times | \d{3,} | 123, 1234, 12345 |
2. Greedy vs Lazy Matching
By default, quantifiers are greedy — they match as much as possible. Add a ? after the quantifier to make it lazy — matching as little as possible:
const html = "<b>Bold</b> and <i>Italic</i>";
// Greedy: matches from first < to last >
html.match(/<.+>/)[0]; // "<b>Bold</b> and <i>Italic</i>"
// Lazy: matches each tag individually
html.match(/<.+?>/g); // ["<b>", "</b>", "<i>", "</i>"]3. Practical Examples
// Match a valid port number (1 to 5 digits)
/:\d{1,5}/.test(":3000"); // true
/:\d{1,5}/.test(":65536"); // true (pattern match only; you'd add boundary ^ and $ for full validation)
// Match an optional https prefix
/https?:\/\//.test("http://example.com"); // true
/https?:\/\//.test("https://example.com"); // truePublished on Last updated: