J

JavaScript Handbook

Clean • Professional

RegEx Quantifiers in JavaScript

1 minute

Regular Expression (RegExp) Quantifiers

In JavaScript, quantifiers define how many times a character, group, or character class must appear in a string for a match. They make regular expressions flexible and allow for precise or repeated pattern matching.

1. Basic Quantifiers

QuantifierMeaningExample
*Matches 0 or more occurrences of the preceding character/group/class"caat".match(/ca*t/) → ["caat"] "ct".match(/ca*t/) → ["ct"]
+Matches 1 or more occurrences"caat".match(/ca+t/) → ["caat"] "ct".match(/ca+t/) → null
?Matches 0 or 1 occurrence (optional)"cat".match(/ca?t/) → ["cat"] "ct".match(/ca?t/) → ["ct"]
{n}Matches exactly n occurrences"caaat".match(/ca{3}t/) → ["caaat"] "cat".match(/ca{3}t/) → null
{n,}Matches n or more occurrences"caaaat".match(/ca{2,}t/) → ["caaaat"] "cat".match(/ca{2,}t/) → null
{n,m}Matches between n and m occurrences"caaat".match(/ca{2,4}t/) → ["caaat"] "caaaaat".match(/ca{2,4}t/) → null

2. Greedy vs Non-Greedy (Lazy) Matching

By default, quantifiers are greedy, matching as much as possible. Adding ? after a quantifier makes it non-greedy (lazy), matching as little as possible.

const str = "<p>text</p><p>more</p>";
console.log(str.match(/<p>.*<\\/p>/));   // Greedy → ["<p>text</p><p>more</p>"]
console.log(str.match(/<p>.*?<\\/p>/g)); // Non-greedy → ["<p>text</p>", "<p>more</p>"]

3. Applying Quantifiers to Groups and Classes

Quantifiers can apply to:

  • Single characters/a+/ matches one or more 'a'
  • Character classes/[0-9]+/ matches one or more digits
  • Groups/(ab)+/ matches one or more "ab" sequences
console.log("ababab".match(/(ab)+/)); // ["ababab", "ab"]
console.log("12345".match(/[0-9]+/)); // ["12345"]

Practical Examples

Phone Number Matching:

const str = "123-456-7890";
console.log(str.match(/\\d{3}-\\d{3}-\\d{4}/)); // ["123-456-7890"]

Optional Protocol in URL:

const str = "<http://example.com>";
console.log(str.match(/https?:\\/\\//)); // ["http://"] (0 or 1 's')

Repeated Words:

const str = "hello hello hello";
console.log(str.match(/(hello\s*){2,}/)); // ["hello hello hello", "hello "]

 

Article 0 of 0