Quantifiers
Learn to specify repetition with *, +, ? and {}.
Quantifiers: * + ?
A quantifier says how many times a pattern piece may repeat. The three basic ones are:
*— zero or more+— one or more?— zero or one (optional)
/a+/.test("baaa"); // true
/colou?r/.test("color"); // trueA quantifier applies to the character or class right before it. This lets you write repeated structures in a short form.
Repeat count: {n}
Curly braces give an exact repeat count: {n} exactly n times, {n,} at least n times, {n,m} between n and m times.
/\d{4}/.test("2024"); // true
/\d{3,5}/.test("12345"); // trueThis is how you express precise conditions like "exactly 4 digits" or "3 to 5 digits". It is very useful for validating PINs or ZIP codes.
Exercise Validate a ZIP code
Assign a regex literal matching exactly 5 digits to zipPattern. Then test it on the string "90210" with .test() and log the result with console.log.
Show example solution
/\d{5}/.
Example solution:
let zipPattern = /\d{5}/;
console.log(zipPattern.test("90210"));
Test yourself
-
Which quantifier means 'zero or more' repetitions?
- *
- +
- ?
- {}
Show answer
* — Correct! * (star) means zero or more repetitions.
-
Match exactly 3 digits
const code = ____; console.log(code.test("abc123"));Show answer
const code = /\d{3}/; console.log(code.test("abc123")); -
Match quantifiers with their meaning
- *
- zero or more
- +
- one or more
- ?
- zero or one
- {3}
- exactly 3 times
-
What does the ? quantifier mean?
- zero or more
- one or more
- exactly one
- zero or one (optional)
Show answer
zero or one (optional) — Correct! ? means zero or one, that is, optional.