Last Updated : 11 Jul, 2025
The ? quantifier in JavaScript regular expressions specifies that the preceding element is optional. It matches zero or one occurrence of the element, making it a useful tool for flexible pattern matching.
JavaScript
let regex = /colou?r/;
let str1 = "color";
let str2 = "colour";
let str3 = "colouur";
console.log(regex.test(str1));
console.log(regex.test(str2));
console.log(regex.test(str3));
The pattern /colou?r/ matches both "color" and "colour" because the u is optional. It does not match "colouur" because it has more than one u.
Syntax:element?
let regex = /behaviou?r/;
console.log(regex.test("behavior"));
console.log(regex.test("behaviour"));
console.log(regex.test("behaviours"));
Matches "behavior" and "behaviour" but not "behaviours".
2. Optional Groups JavaScript
let regex = /(?:https?:\/\/)?www\.\w+\.\w+/;
console.log(regex.test("https://www.example.com/"));
console.log(regex.test("www.example.com"));
console.log(regex.test("example.com"));
The https?:// group is optional, so the pattern matches URLs with or without "http://" or "https://".
3. Matching Optional Digits JavaScript
let regex = /\d{3}-?\d{4}/;
console.log(regex.test("123-4567"));
console.log(regex.test("1234567"));
console.log(regex.test("123--4567"));
The - is optional, so the pattern matches phone numbers with or without a hyphen.
4. Making a Case-Insensitive Match JavaScript
let regex = /[A-Z]?pple/i;
console.log(regex.test("Apple"));
console.log(regex.test("pple"));
console.log(regex.test("aPple"));
The optional [A-Z] allows for matching "Apple" or "pple".
5. Validating Postal Codes JavaScript
let regex = /\d{5}(-\d{4})?/;
console.log(regex.test("12345"));
console.log(regex.test("12345-6789"));
console.log(regex.test("123456789"));
Matches U.S. ZIP codes with or without the four-digit extension.
Common Patterns Using ?/colou?r/
/(?:https?:\/\/)?www\.\w+\.\w+/
/\d{3}-?\d{4}/
/[A-Z]?pple/i
/\d{5}(-\d{4})?/Limitations
The ? quantifier is a powerful and versatile tool for making elements optional in regular expressions, enabling flexible and precise pattern matching.
Recommended Links:RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4