JavaScript RegExp Quantifiers

Specify how many times patterns should match

🔢 What are Quantifiers?

Quantifiers specify how many times a character or group should be matched. They make your patterns flexible by allowing repetition without writing the same pattern multiple times.


// Quantifiers specify repetition
let pattern = /\d{3}/;  // Exactly 3 digits
let text = "Call 555-1234";
console.log(text.match(pattern)); // ["555"]
                                    

Types of Quantifiers

* - Zero or More

Matches 0 or more occurrences

a* 0 to ∞

+ - One or More

Matches 1 or more occurrences

a+ 1 to ∞

? - Zero or One

Matches 0 or 1 occurrence (optional)

a? Optional
🎯

{n,m} - Range

Matches between n and m times

{2,5} Exact range

🔹 Star Quantifier (*) - Zero or More

The * quantifier matches zero or more of the preceding character:

let text = "aaa bb cccc d";

// Match 'a' followed by zero or more 'a's
let aPattern = /a*/g;
console.log(text.match(aPattern)); // ["aaa", "", "", "", "", "", "", "", "", "", "", "", ""]

// More practical: match word followed by optional 's'
let words = "cat cats dog dogs";
let singularPlural = /\w+s*/g;
console.log(words.match(singularPlural)); // ["cat", "cats", "dog", "dogs"]

// Match numbers with optional decimal part
let numbers = "5 3.14 42 7.5";
let numberPattern = /\d+\.?\d*/g;
console.log(numbers.match(numberPattern)); // ["5", "3.14", "42", "7.5"]

Output:

Words: ["cat", "cats", "dog", "dogs"]

Numbers: ["5", "3.14", "42", "7.5"]

🔹 Plus Quantifier (+) - One or More

The + quantifier matches one or more of the preceding character:

let text = "a aa aaa b bb";

// Match one or more 'a's
let aPattern = /a+/g;
console.log(text.match(aPattern)); // ["a", "aa", "aaa"]

// Match sequences of digits
let mixed = "abc123def456ghi";
let digits = mixed.match(/\d+/g);
console.log(digits); // ["123", "456"]

// Match words (one or more word characters)
let sentence = "Hello, world! How are you?";
let words = sentence.match(/\w+/g);
console.log(words); // ["Hello", "world", "How", "are", "you"]

Output:

A sequences: ["a", "aa", "aaa"]

Digits: ["123", "456"]

Words: ["Hello", "world", "How", "are", "you"]

🔹 Question Mark (?) - Zero or One

The ? quantifier makes the preceding character optional:

// Match "color" or "colour"
let text1 = "I like the color red";
let text2 = "I like the colour red";
let pattern = /colou?r/;
console.log(pattern.test(text1)); // true
console.log(pattern.test(text2)); // true

// Match optional "s" for plurals
let items = "1 cat, 2 cats, 1 dog, 3 dogs";
let pattern2 = /\d+ \w+s?/g;
console.log(items.match(pattern2)); // ["1 cat", "2 cats", "1 dog", "3 dogs"]

// Match optional protocol in URLs
let urls = ["http://example.com", "https://example.com", "example.com"];
let urlPattern = /https?:\/\/\w+\.\w+/;
urls.forEach(url => {
    console.log(`${url}: ${urlPattern.test(url)}`);
});

Output:

Color/Colour: both match

Items: ["1 cat", "2 cats", "1 dog", "3 dogs"]

URLs: http and https both match

🔹 Curly Braces {} - Exact Counts

Use curly braces to specify exact repetition counts:

let text = "Phone: 555-123-4567";

// Exactly 3 digits
let areaCode = text.match(/\d{3}/);
console.log(areaCode[0]); // "555"

// Between 2 and 4 digits
let numbers = "1 22 333 4444 55555";
let twoToFour = numbers.match(/\d{2,4}/g);
console.log(twoToFour); // ["22", "333", "4444", "5555"] (note: 55555 matches first 4)

// At least 3 digits
let atLeastThree = numbers.match(/\d{3,}/g);
console.log(atLeastThree); // ["333", "4444", "55555"]

// Validate ZIP codes (exactly 5 digits)
let zipPattern = /^\d{5}$/;
console.log(zipPattern.test("12345")); // true
console.log(zipPattern.test("1234")); // false

Output:

Area code: "555"

2-4 digits: ["22", "333", "4444", "5555"]

ZIP validation: true for "12345"

🔹 Greedy vs Lazy Quantifiers

By default, quantifiers are greedy. Add ? to make them lazy:

let html = '
Hello
World
'; // Greedy: matches as much as possible let greedy = html.match(/
.*<\/div>/); console.log(greedy[0]); // "
Hello
World
" // Lazy: matches as little as possible let lazy = html.match(/
.*?<\/div>/); console.log(lazy[0]); // "
Hello
" // Get all div contents with lazy matching let allDivs = html.match(/
.*?<\/div>/g); console.log(allDivs); // ["
Hello
", "
World
"] // Extract content between quotes let text = 'He said "Hello" and she said "Goodbye"'; let quotes = text.match(/".*?"/g); console.log(quotes); // ['"Hello"', '"Goodbye"']

Output:

Greedy: matches entire string

Lazy: matches individual divs

Quotes: ['"Hello"', '"Goodbye"']

🔹 Practical Examples

Common uses of quantifiers in real applications:

Phone Number Validation:

// US phone: (123) 456-7890 or 123-456-7890
let phonePattern = /^$$?\d{3}$$?[-.\s]?\d{3}[-.\s]?\d{4}$/;
console.log(phonePattern.test("(555) 123-4567")); // true
console.log(phonePattern.test("555-123-4567")); // true

Password Strength:

// At least 8 chars, with letters and numbers
let passwordPattern = /^(?=.*[a-zA-Z])(?=.*\d).{8,}$/;
console.log(passwordPattern.test("password123")); // true
console.log(passwordPattern.test("pass")); // false

Extract Repeated Words:

// Find words that appear 2+ times
let text = "the cat and the dog and the bird";
let repeatedWords = text.match(/\b(\w+)\b(?=.*\b\1\b)/g);
console.log(repeatedWords); // ["the", "and", "the", "and"]

🧠 Test Your Knowledge

What does the + quantifier match?