JavaScript RegExp ? Quantifier

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Zero or one

What You’ll Learn

The ? quantifier makes the previous token optional—it matches zero or one time. Use it for optional letters (https?), optional signs (-?\d+), optional prefixes, and flexible patterns without writing two separate regexes.

01

?

Zero or one

02

{0,1}

Same meaning

03

Optional

May skip

04

(grp)?

Whole group

05

Not (?=)

Quantifier

06

https?

Classic use

Introduction

Real text is messy: URLs may use http or https, numbers may have an optional minus sign, and names may include an optional title. The ? quantifier handles all of these with one pattern by saying “this part may appear once, or not at all.”

Do not confuse ? the quantifier with ? in lookaheads like (?=...) or (?!...). When ? follows a character or group, it controls repetition. When it immediately follows ( at the start of a special construct, it begins a lookahead assertion—a different feature entirely.

Understanding the ? Quantifier

Place ? right after a token. The engine tries to match that token once; if that helps the overall pattern, it uses it. Otherwise it skips it (zero times) and continues. Both outcomes are valid.

JavaScript
const urls = ["http://a.com", "https://b.com", "ftp://c.com"];

urls.forEach((url) => {
  console.log(url, /^https?/.test(url));
});
// http://a.com   true
// https://b.com  true
// ftp://c.com    false

In https?, the ? applies only to s—so s is optional. The pattern matches http and https but not ftp.

💡
Beginner Tip

To make several characters optional together, wrap them in a group: (abc)? not abc? (which only optionalizes c).

How to Use the ? Quantifier

Attach ? to single characters, escaped literals, or grouped sequences:

JavaScript
/https?/;                 // http or https
/-?\d+/;                  // optional minus on numbers
/colou?r/;                // color or colour
/(Mr\. )?Smith/;         // optional title
/(www\.)?example\.com/; // optional www.

"colour".match(/colou?r/); // ["colour"]

Combine with anchors for validation, or with the global flag to find every optional match in a string. Use ?? for the lazy form (prefer skipping when possible).

📝 Syntax

JavaScript
token?           // zero or one of token
https?           // s is optional
(group)?         // entire group optional
token{0,1}       // equivalent to ?
token??          // lazy — prefer zero

Common patterns

  • /https?/ — match http or https.
  • /-?\d+/ — integers with optional leading minus.
  • /colou?r/ — American or British spelling.
  • /(www\.)?example\.com/ — domain with optional www..
  • /\.jpe?g$/i.jpg or .jpeg extension.

⚡ Quick Reference

GoalPattern / API
Optional characters?
Optional group(abc)?
Optional minus sign-?\d+
Longhand form{0,1}
Lazy optional??
At most oneUnlike * (unlimited repeats)

📋 ? vs + vs *

Three repetition quantifiers and how many times the token may appear.

?
token?

Zero or one — optional

+
token+

One or more — required

*
token*

Zero or more — unlimited

On "a"
/a?/

Matches (zero times) — empty match

Examples Gallery

Open DevTools Console (F12) or use Try-it links. Examples cover optional protocol letters, spelling variants, signed numbers, optional groups, and file extensions.

📚 Getting Started

Make a single character optional.

Example 1 — Match http or https with https?

The classic optional-s pattern for web URLs.

JavaScript
const urls = ["http://site.com", "https://secure.com", "ftp://files.com"];

urls.forEach((url) => {
  console.log(url, /^https?/.test(url));
});
// http://site.com    true
// https://secure.com true
// ftp://files.com    false
Try It Yourself

How It Works

The ? applies only to s. The engine matches http and optionally adds s when present. This is shorter than writing (http|https) for this case.

📈 Practical Patterns

Spelling, numbers, groups, and filenames.

Example 2 — American or British Spelling with colou?r

Match color and colour with one pattern.

JavaScript
const words = ["color", "colour", "coloor"];

words.forEach((w) => {
  console.log(w, /colou?r/.test(w));
});
// color  true
// colour true
// coloor false
Try It Yourself

How It Works

Only the letter u is optional. coloor fails because extra o characters are not allowed by the pattern.

Example 3 — Optional Minus Sign with -?\d+

Match positive and negative integers.

JavaScript
const values = ["42", "-7", "abc", "3.14"];

values.forEach((v) => {
  console.log(v, /^-?\d+$/.test(v));
});
// 42   true
// -7   true
// abc  false
// 3.14 false
Try It Yourself

How It Works

-? makes the minus sign optional. \d+ requires one or more digits. Anchors ^ and $ ensure the whole string is a plain integer.

Example 4 — Optional Prefix Group (Mr\. )?

Match a name with or without an honorific prefix.

JavaScript
const names = ["Smith", "Mr. Smith", "Mrs. Smith"];

names.forEach((n) => {
  console.log(n, /^(Mr\. )?Smith$/.test(n));
});
// Smith       true
// Mr. Smith   true
// Mrs. Smith  false
Try It Yourself

How It Works

Parentheses group Mr. as one unit; ? makes the entire prefix optional. Without the group, Mr\. ?Smith would only optionalize the space after the dot.

Example 5 — Optional Letter in File Extension \.jpe?g

Accept both .jpg and .jpeg filenames.

JavaScript
const isJpeg = /\.jpe?g$/i;

console.log(isJpeg.test("photo.jpg"));   // true
console.log(isJpeg.test("photo.jpeg"));  // true
console.log(isJpeg.test("photo.png"));   // false
Try It Yourself

How It Works

The optional e covers both three- and four-letter extensions. Combined with $, nothing may follow the extension.

🚀 Common Use Cases

  • URL protocolshttps? for http and https.
  • Signed numbers-?\d+ for optional negative values.
  • Spelling variants — optional letters for US/UK English.
  • Optional prefixes(www\.)?, titles, or namespace segments.
  • File extensions\.jpe?g, \.docx? style patterns.
  • Flexible formats — optional separators, padding, or suffix characters.

Important Considerations

  • Scopeabc? optionalizes only c; use (abc)? for the whole sequence.
  • Not lookahead? after a token repeats; (?=...) is a separate assertion syntax.
  • Empty matches/a?/ can match zero characters at a position; use anchors to avoid surprises.
  • At most one — unlike *, ? never repeats the token twice.
  • Lazy form?? prefers skipping the optional token when both paths work.
  • Greedy default? tries to match the token once before skipping when both succeed.

🧠 How the ? Quantifier Works

1

Reach the token

The engine arrives at the character or group before ?.

Position
2

Try one match

Greedy mode attempts to consume the token once and continues the pattern.

Try 1
3

Or skip (zero)

If matching once fails—or backtracking requires it—the engine skips the token entirely.

Try 0
4

Continue pattern

Either branch may succeed. The rest of the regex determines which path wins.

📝 Notes

  • ? equals {0,1}—optional, at most once.
  • Previous topic: (?=...) positive lookahead.
  • Next topic: * zero-or-more quantifier.
  • See + for one-or-more repetition.
  • See (x|y) alternation when optional choices are not simple zero-or-one.
  • Lazy quantifiers: +?, *?, and ?? prefer shorter matches.

Browser & Runtime Support

The ? quantifier is part of core JavaScript regular expression syntax.

Baseline · ES3+

RegExp ? quantifier

Supported in every browser and Node.js version. Use ? to make tokens optional in patterns.

99% Universal syntax
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
? Excellent

Bottom line: Safe everywhere. ? is the standard way to match zero or one of a token.

Conclusion

The ? quantifier makes the previous token optional: zero or one occurrence. It powers familiar patterns like https? and -?\d+, and keeps regexes concise when a part of the input may or may not appear.

Remember to group multi-character optionals with parentheses, distinguish ? the quantifier from lookahead (?=...), and reach for * or + when you need more than one repetition. Next, learn the * quantifier.

💡 Best Practices

✅ Do

  • Use ? when a token may appear at most once
  • Wrap multi-char optionals: (prefix)?
  • Combine with anchors for strict validation patterns
  • Prefer https? over (http|https) when only one char differs
  • Test both present and absent cases for each optional part

❌ Don’t

  • Confuse ? quantifier with (?=...) lookahead
  • Write abc? when you mean (abc)?
  • Use ? when the token can repeat many times—use * or +
  • Forget that ? can match empty (zero times)
  • Overuse optionals when alternation lists are clearer

Key Takeaways

Knowledge Unlocked

Five things to remember about the RegExp ? quantifier

Make parts of your pattern optional with zero-or-one matching.

5
Core concepts
📈 02

{0,1}

Same rule.

Shorthand
📄 03

(grp)?

Group optional.

Group
🔒 04

https?

Classic.

Pattern
🚫 05

Not (?=)

Lookahead.

Pitfall

❓ Frequently Asked Questions

The ? quantifier means zero or one of the preceding token. It makes that token optional. For example, https? matches both http and https because the s is optional.
Yes. ? is shorthand for {0,1}—the preceding item may appear once or not at all. Both are greedy by default in JavaScript.
After a token or group, ? is a quantifier (optional repetition). After an opening parenthesis at the start of a group like (?=...), ? begins a lookahead assertion—not optional matching. Context determines the meaning.
? allows zero or one repetition. * allows zero or more. Use ? when something may appear at most once; use * when it can repeat many times.
Yes. (abc)? makes the entire group optional—it matches once or skips it entirely. Example: (Mr\. )?Smith matches Smith and Mr. Smith.
The ? quantifier is core JavaScript regex syntax since ES3. It works in every browser and Node.js version without polyfills.
Did you know?

The pattern https? is one of the most copied regex snippets on the web. It works because ? binds tightly to the immediately preceding token—here, just the letter s—not to the entire word https.

Continue to * zero-or-more quantifier

Learn how * repeats the previous token zero or more times.

* quantifier tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful