Course contentsShow
← JavaScript
Lesson 1683 of 2,72336. Regular ExpressionsFree lesson

The Star Quantifier

Match zero or more occurrences with * and understand when it produces empty matches.

The Star Quantifier

You'll learn how * matches zero or more occurrences of a pattern, including surprising cases where it matches nothing at all.

What the Star Does

The star quantifier (*) tells the regex engine to match the preceding character or group zero or more times. Unlike the plus quantifier (+) which requires at least one match, the star is more permissive—it succeeds even when the pattern appears zero times.

Think of it like asking "How many cookies do you want?" with no minimum requirement. The answer could be "five cookies," "one cookie," or even "zero cookies"—all valid responses.

Zero-Length Matches Matter

The "zero" part is crucial. Consider this pattern:

const pattern = /a*/;
console.log(pattern.test("aaa"));   // true (matches "aaa")
console.log(pattern.test("b"));     // true (matches empty string)
console.log(pattern.test(""));      // true (matches empty string)

Every string passes the test because a* can match zero a characters. When there's no a present, the regex successfully matches an empty string at the start position.

Practical Usage

The star quantifier becomes powerful when combined with other patterns:

const whitespace = /\s*/;
console.log("  hello".match(whitespace));  // ["  "] - matches leading spaces

const optional = /colou*r/;
console.log(optional.test("color"));   // true
console.log(optional.test("colour"));  // true

const trailing = /\d+\s*$/;
console.log(trailing.test("123"));     // true (digit(s), then optional spaces)
console.log(trailing.test("123   ")); // true

Key Takeaway: The star quantifier (*) matches zero or more occurrences, making patterns optional but still allowing unlimited repetition—beware that it always succeeds, even when matching nothing.