RegExp quantifiers in JavaScript define how many times a character, group, or pattern should repeat. They control repetition and are essential for matching variable-length text like numbers, words, and formatted input. Quantifiers make patterns flexible and precise.
What Are RegExp Quantifiers?
Quantifiers specify the number of occurrences allowed for the preceding token (character, group, or class).
Common quantifiers:
Asterisk * — Zero or More
Matches the previous token zero or more times.
Explanation:
Matches col, cool, and coool.
Plus + — One or More
Matches the previous token one or more times.
Explanation:
Matches cool but not col.
Question Mark ? — Zero or One (Optional)
Makes the previous token optional.
Explanation:
Matches both color and colour.
Exact Count {n}
Matches the previous token exactly n times
Explanation:
Matches only if there are exactly 4 digits.
At Least {n,}
Matches the previous token at least n times.
Explanation:
Matches two or more occurrences of a.
Range {n,m}
Matches the previous token between n and m times.
Explanation:
Matches if a appears between 2 and 4 times.
Greedy vs Lazy Quantifiers
By default, quantifiers are greedy and try to match as much as possible.
Adding ? after a quantifier makes it lazy, matching as little as possible.
Explanation:
.*? matches the smallest possible content between < and >.
Applying Quantifiers to Groups
Quantifiers can be applied to grouped patterns.
Explanation:
Matches ab repeated 2 to 3 times.
Common Mistakes with Quantifiers
-
Forgetting that quantifiers apply only to the previous token
-
Using greedy quantifiers where lazy matching is required
-
Not anchoring patterns with
^and$for full-string validation -
Misusing
{n,m}ranges
Summary of RegExp Quantifiers
| Quantifier | Meaning |
|---|---|
* | Zero or more |
+ | One or more |
? | Zero or one |
{n} | Exactly n |
{n,} | At least n |
{n,m} | Between n and m |
*? +? | Lazy versions |
Conclusion
RegExp quantifiers in JavaScript control how many times a pattern can repeat, making regular expressions powerful for matching variable-length text. By choosing the right quantifier and understanding greedy versus lazy behavior, pattern matching becomes more accurate and reliable in JavaScript applications.