JS RegExp Quantifiers

JavaScript RegExp Quantifiers

Quantifiers in regular expressions define how many times a character, group, or character class must be present in the string for a match to be found.


Essential Quantifiers

Quantifier Description
* Matches zero or more times.
+ Matches one or more times (must appear at least once).
? Matches zero or one time (makes the character optional).
{n} Matches exactly n times.
{n,} Matches at least n times.
{n,m} Matches between n and m times.

1. The Core Quantifiers: *, +, and ?

These are the most frequently used quantifiers in programming.

Quantifier Examples

let text1 = "Hellooo!";
let text2 = "Color or colour?";

// Match 'o' one or more times (+) console.log(text1.match(/o+/g)); // ["ooo"]

// Match 'u' zero or one time (?) -> makes 'u' optional! // This matches both American and British spellings! console.log(text2.match(/colou?r/gi)); // ["Color", "colour"]


2. Curly Braces Quantifiers {n,m}

When you need extreme precision over quantity, you use curly braces. This is perfect for validating structured data like phone numbers or zip codes.

Validating a 5-Digit Zip Code

// The ^ and $ assert the entire string must match the pattern
// \d{5} asserts exactly 5 digits must be present.

let regex = /^\d{5}$/;

console.log(regex.test("12345")); // true console.log(regex.test("123456")); // false (too long) console.log(regex.test("123a5")); // false (contains a letter)


3. Greedy vs. Lazy Quantifiers

By default, quantifiers in JavaScript are greedy. This means they will try to match as many characters as possible.

Sometimes, this is not what you want. If you add a question mark ? directly after a quantifier (like +? or *?), it becomes lazy, meaning it will match as few characters as possible.

Greedy vs Lazy Example

let text = '<h1>Hello</h1>';

// Greedy: matches from the first < all the way to the LAST > let greedy = text.match(/<.*>/); console.log(greedy[0]); // "<h1>Hello</h1>"

// Lazy: matches from the first < to the FIRST > it finds let lazy = text.match(/<.*?>/); console.log(lazy[0]); // "<h1>"