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

The Question Mark Quantifier

Make patterns optional by matching zero or one occurrence using the ? quantifier.

The Question Mark Quantifier

You'll learn how to make parts of your regex pattern optional, matching either zero or one occurrence.

What Makes Something Optional?

In regular expressions, the question mark (?) quantifier means "match the preceding character or group zero or one time." In other words, it makes something optional—it can be there, or it can be absent, and your pattern will still match.

Think of it like ordering a sandwich: "lettuce?" means you're fine with or without lettuce. The sandwich is valid either way.

How It Works

Place ? immediately after the character, character class, or group you want to make optional:

const pattern = /colou?r/;

pattern.test("color");   // true (zero 'u')
pattern.test("colour");  // true (one 'u')
pattern.test("colouur"); // false (two 'u's — too many!)

The u? means "match zero or one 'u'." This is perfect for handling spelling variations like American vs British English.

Practical Examples

Making whole groups optional:

const datePattern = /\d{1,2}(st|nd|rd|th)?/;

datePattern.test("21st");  // true
datePattern.test("21");    // true (suffix is optional)
datePattern.test("3rd");   // true
datePattern.test("15");    // true

Matching URLs with optional protocols:

const urlPattern = /https?:\/\//;

urlPattern.test("http://");  // true
urlPattern.test("https://"); // true (the 's' is optional)

When to Use ? vs *

Remember: * matches zero or more (unlimited), while ? matches zero or one (optional but limited). Use ? when something should appear at most once.

Key Takeaway: The ? quantifier makes the preceding element optional by matching it zero or one time—perfect for handling variations and optional parts of patterns.