JavaScript RegExp ? Quantifier Last Updated : 10 Dec, 2024 Comments Improve Suggest changes Like Article Like Report 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)); Outputtrue true false 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?element: The character, group, or character class to be made optional.Key PointsMatches zero or one occurrence of the preceding element.Useful for optional letters or segments in words.Can apply to individual characters or grouped patterns.Real-World Examples1. Optional Characters in Words JavaScript let regex = /behaviou?r/; console.log(regex.test("behavior")); console.log(regex.test("behaviour")); console.log(regex.test("behaviours")); Outputtrue true true 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")); Outputtrue true false The https?:// group is optional, so the pattern matches URLs with or without "https://" 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")); Outputtrue true false 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")); Outputtrue true true 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")); Outputtrue true true Matches U.S. ZIP codes with or without the four-digit extension.Common Patterns Using ?Optional Characters in Words:/colou?r/Optional Group in a URL:/(?:https?:\/\/)?www\.\w+\.\w+/Phone Numbers with Optional Separators:/\d{3}-?\d{4}/Case Insensitivity for a Letter:/[A-Z]?pple/iPostal Codes with Optional Extensions:/\d{5}(-\d{4})?/LimitationsMatches Only Once: Unlike the * quantifier (zero or more) or + (one or more), ? matches at most one occurrence.Limited for Repeating Patterns: Use other quantifiers (*, +, {}) for patterns that require multiple matches.Why Use the ? Quantifier?Flexibility: Handles optional elements gracefully.Readability: Keeps patterns concise and easy to understand.Real-World Use Cases: Essential for handling variable text structures like optional URL protocols, postal code extensions, or flexible word spellings.ConclusionThe ? quantifier is a powerful and versatile tool for making elements optional in regular expressions, enabling flexible and precise pattern matching.Recommended Links:JavaScript RegExp Complete ReferenceJavaScript Cheat Sheet-A Basic guide to JavaScriptJavaScript Tutorial Comment More infoAdvertise with us Next Article JavaScript RegExp + Quantifier V Vishal Chaudhary 2 Follow Improve Article Tags : JavaScript Web Technologies JavaScript-RegExp Similar Reads JavaScript RegExp() Constructor The RegExp() constructor in JavaScript allows you to create a regular expression object that can be used to match patterns in strings. This method is particularly useful when you need to dynamically create regular expressions from strings or variables. JavaScriptlet pat = "hello"; let regex = new Re 2 min read JS RegExp PropertiesJavaScript RegExp Constructor PropertyThe constructor property of a JavaScript RegExp object returns a reference to the function that created the regular expression. This property typically points to the built-in RegExp function.JavaScript// Creating a regular expression let regex = /test/; // Checking the constructor property console.l 2 min read JavaScript RegExp dotAll PropertyThe dotAll property in JavaScript regular expressions determines whether the 's' (dotAll) flag is enabled. This flag modifies the behaviour of the dot (.) metacharacter, allowing it to match any character, including line terminators like \n, \r, and others. Without the s flag, the dot (.) matches an 2 min read JavaScript RegExp Flags PropertyRegExp flags are a set of optional characters added to the regular expression pattern to control its behavior. Flags modify how the pattern is interpreted during the search. They can be added after the closing / of the regular expression pattern.JavaScriptlet s = "Hello World\nhello world"; // Globa 3 min read JavaScript RegExp global PropertyThe global property in JavaScript regular expressions indicates whether the g (global) flag is enabled. A regular expression with the g flag searches for all matches in the input string rather than stopping after the first match.JavaScript// Regular expression without 'g' flag let regex1 = /test/; c 2 min read JavaScript RegExp hasIndices PropertyThe hasIndices property in JavaScript regular expressions indicates whether the d (indices) flag is enabled. When the d flag is set, the regular expression captures the start and end indices of the matched substring within the input string, providing detailed positional information.JavaScript// Regu 3 min read JavaScript RegExp ignoreCase PropertyThe ignoreCase property in JavaScript regular expressions determines whether the i (ignore case) flag is enabled. A regular expression with the i flag performs a case-insensitive match, meaning it ignores differences between uppercase and lowercase characters during the matching process.JavaScript// 2 min read JavaScript RegExp multiline PropertyThe multiline property of a JavaScript regular expression indicates whether the m (multiline) flag is enabled. When enabled, the ^ and $ anchors match the start and end of each line within a string, rather than the entire string.JavaScript// Regular expression without 'm' flag let regex1 = /^test$/; 2 min read JavaScript RegExp source PropertyThe source property of a JavaScript regular expression object returns the text of the pattern used to create the RegExp object, without the enclosing slashes or flags. This property is read-only and reflects the original pattern as a string.JavaScript// Creating a regular expression let regex = /hel 2 min read JavaScript RegExp Sticky PropertyThe sticky property in JavaScript regular expressions determines whether the y (sticky) flag is enabled. A sticky regular expression searches for a match starting from the current position in the target string and does not search further if a match isn't found at that exact point.JavaScript// Regula 3 min read JavaScript RegExp unicode PropertyThe unicode property of a JavaScript regular expression object indicates whether the u (Unicode) flag is enabled. When this flag is set, the regular expression operates in full Unicode mode, allowing correct handling of Unicode characters, such as surrogate pairs, Unicode code points, and properties 2 min read JavaScript RegExp lastIndex PropertyThe lastIndex property of a JavaScript regular expression object indicates the index at which to start the next match. This property is particularly useful when using methods like exec() or test() in combination with global (g) or sticky (y) flags.JavaScriptlet regex = /test/g; // Regular expression 3 min read JS RegExp MethodsJavaScript RegExp exec() MethodThe RegExp.exec() method in JavaScript allows you to search for a pattern in a string and retrieve detailed information about the match. Unlike simple methods like test(), exec() returns not just a boolean, but an array containing the entire match, capturing groups, the position of the match, and mo 2 min read JavaScript RegExp test() MethodThe RegExp test() Method in JavaScript is used to test for match in a string. If there is a match this method returns true else it returns false.JavaScriptconst pattern = /hello/; const text = "hello world"; console.log(pattern.test(text));Outputtrue SyntaxRegExpObject.test(str)Where str is the stri 1 min read JavaScript RegExp toString() MethodThe RegExp.toString() method in JavaScript is used to return the string representation of a regular expression object. It converts the regular expression to a string, including its pattern and flags. JavaScriptlet reg1 = /hello/i; let reg2 = /\d{3}-\d{2}-\d{4}/; console.log(reg1.toString()); console 2 min read JS RegExp QuantifierJavaScript RegExp ? QuantifierThe ? 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.JavaScriptlet regex = /colou?r/; let str1 = "color"; let str2 = "colour"; let str3 = "colouur"; 2 min read JavaScript RegExp + QuantifierThe m+ Quantifier in JavaScript is used to find the match of any string that contains at least one m. JavaScriptlet str = "GeeksforGeeks@_123_$"; let regex = /G+/gi; let match = str.match(regex); console.log("Found " + match.length + " matches: " + match);Syntax: /m+/ Example 1: Matches the presence 1 min read JavaScript RegExp * QuantifierThe RegExp m* Quantifier in JavaScript is used to find the match of any string that contains zero or more occurrences of match. JavaScriptlet str = "GeeksforGeeks@_123_G$"; let regex = /ke*/gi; let match = str.match(regex); console.log("Found " + match.length + " matches: " + match);OutputFound 2 ma 1 min read JavaScript RegExp ?! QuantifierThe RegExp ?!m Quantifier in JavaScript is used to find the match of any string which is not followed by a specific string m. JavaScript// 3-digits not followed by any numbers const str = "123Geeks12345@"; const regex = /\d{3}(?!\d)/g; const match = str.match(regex); console.log(match); Output[ '123 1 min read JavaScript RegExp ^ QuantifierThe ^ in JavaScript regular expressions is a special anchor that matches the beginning of a string or the start of a line when the multiline (m) flag is used. It is not a quantifier but an assertion used to control where matching starts in a string.JavaScriptlet regex = /^hello/; let str1 = "hello w 2 min read JavaScript RegExp $ QuantifierThe RegExp m$ Quantifier in JavaScript is used to find the match of any string which contains m at the end of it. JavaScriptlet str = "Geeksforh\nGeeks@_h"; let regex = /h$/gim; let match = str.match(regex); console.log("Found " + match.length + " matches: " + match);Syntax: /m$/ Example 1: Matches 1 min read JavaScript RegExp {X,} QuantifierThe RegExp m{X, } Quantifier in JavaScript is used to find the match of any string that contains a sequence of m, at least X times, where X is a number.JavaScriptlet str = "GeeksforGeeeks e@_123_$"; let regex = /k{1,}/gi; let match = str.match(regex); console.log("Found " + match.length + " matches: 1 min read JavaScript RegExp {X} QuantifierThe RegExp m{X} Quantifier in JavaScript is used to find the match of any string that contains a sequence of m, X times where X is a number. JavaScriptlet str = "Geekkkksss@_123_$"; let regex = /k{2}/gi; let match = str.match(regex); console.log(match);Output[ 'kk', 'kk' ] Syntax: /m{X}/ // ornew Re 1 min read JavaScript RegExp {X,Y} QuantifierJavaScript RegExp {X,Y} Quantifier in JavaScript is used to find the match of any string that contains a sequence of m, X to Y times where X, Y must be numbered. JavaScript// Matches between 2 and 4 digits const regex = /\d{2,4}/; console.log(regex.test("123")); console.log(regex.test("12345")); con 1 min read JS RegExp ModifierJavaScript RegExp g ModifierThe g (global) modifier in JavaScript regular expressions is used to perform a global search. It ensures the pattern is matched multiple times throughout the entire string, rather than stopping at the first match.JavaScriptlet regex = /cat/g; let str = "cat, caterpillar, catch a cat"; let matches = 3 min read JavaScript RegExp i ModifierThe i modifier in JavaScript regular expressions stands for case-insensitivity. It allows the regex to match letters in a string regardless of their case, making it ideal for scenarios where matching should not be case-sensitive, such as user input validation or text search.When the i flag is active 2 min read JavaScript RegExp m ModifierThe m modifier in JavaScript regular expressions stands for "multiline". It alters the behavior of the ^ (caret) and $ (dollar) anchors, allowing them to match the start or end of any line in a multiline string, rather than just the start or end of the entire string.JavaScriptlet regex = /^hello/m; 3 min read JS RegExp ExpressionJavaScript RegExp [abc] ExpressionThe RegExp [abc] Expression in JavaScript is used to search any character between the brackets. The character inside the brackets can be a single character or a span of characters.[A-Z]: It is used to match any character from uppercase A to Z.[a-z]: It is used to match any character from lowercase a 2 min read JavaScript RegExp (x|y) ExpressionThe (x|y) expression in JavaScript regular expressions is used to match either x or y. It acts as an OR operator in regular expressions, allowing you to specify multiple patterns to match.JavaScriptlet regex = /(cat|dog)/g; let str = "I have a cat and a dog."; let matches = str.match(regex); console 2 min read JavaScript RegExp [0-9] ExpressionThe [0-9] expression in JavaScript regular expressions matches any single digit between 0 and 9. It is a character class used to represent a range of numeric characters.JavaScriptlet regex = /[0-9]/g; let str = "abc123xyz"; let matches = str.match(regex); console.log(matches);Output[ '1', '2', '3' ] 3 min read JavaScript RegExp [^0-9] ExpressionThe RegExp [^0-9] Expression in JavaScript is used to search any digit which is not between the brackets. The character inside the brackets can be a single digit or a span of digits. Example: Finding non-digit characters from given stringJavaScriptconst regex = /[^0-9]/g; const str = "Hello123Geeks" 2 min read JS RegExp MetacharacterJavaScript RegExp . MetacharacterThe . metacharacter in JavaScript regular expressions matches any single character except for a newline (\n) or other line terminators, such as \r. It is widely used as a wildcard to represent "any character."JavaScriptlet regex = /c.t/; let str1 = "cat"; let str2 = "cut"; console.log(regex.test(str 3 min read JavaScript RegExp \b MetacharacterThe \b metacharacter in JavaScript regular expressions represents a word boundary, allowing you to match positions where a word begins or ends. A word boundary is the position between a word character (\w: letters, digits, or underscores) and a non-word character (\W: everything else, including spac 2 min read JavaScript RegExp \B MetacharacterThe \B metacharacter in JavaScript regular expressions matches a position where a word boundary does not exist. It is essentially the opposite of the \b (word boundary) metacharacter.JavaScriptlet regex = /\Bcat\B/; let str1 = "concat"; let str2 = "cat"; console.log(regex.test(str1)); console.log(re 2 min read JavaScript RegExp \d MetacharacterIn JavaScript regular expressions, the \d metacharacter is used to match any digit character (0-9). This is a shorthand for the character class [0-9], which matches any single character within the specified range.To begin, let's look at a simple example where we use \d to match digits in a string.Ja 3 min read JavaScript RegExp \D( non-digit characters) MetacharacterThe RegExp \D Metacharacter in JavaScript is used to search non-digit characters i.e all the characters except digits. It is the same as [^0-9]. JavaScriptlet str = "a1234g5g5"; let regex = /\D/g; let match = str.match(regex); console.log("Found " + match.length + " matches: " + match);OutputFound 3 1 min read JavaScript RegExp \f MetacharacterThe \f metacharacter in JavaScript regular expressions matches a form feed character. Form feed (\f) is a control character used to indicate a page break in text. While it is rare in modern applications, it can still appear in old documents or text files.JavaScriptlet regex = /\f/; let str1 = "Hello 2 min read JavaScript RegExp \n MetacharacterThe \n metacharacter in JavaScript regular expressions matches a newline character. It is used to identify line breaks in strings, enabling developers to process multi-line text effectively.JavaScriptlet regex = /\n/; let str = "Hello\nWorld"; console.log(regex.test(str));Outputtrue The pattern \n d 2 min read JavaScript RegExp \v (vertical tab character) MetacharacterThe RegExp \v Metacharacter in JavaScript is used to find the vertical tab character. If it is found it returns the position else it returns -1. JavaScriptlet str = "G\vFG@_123_$"; let regex = /\v/; let match = str.search(regex); if (match == -1) { console.log("No vertical tab character present. "); 1 min read JavaScript RegExp \t MetacharacterThe RegExp \t Metacharacter in JavaScript is used to find the tab character. If it is found it returns the position else it returns -1. JavaScriptlet str = "GFG\t@_123_$"; let regex = /\t/; let match = str.search(regex); if (match == -1) { console.log("No tab character present. "); } else { console. 1 min read JavaScript RegExp \s MetacharacterThe \s metacharacter in JavaScript regular expressions matches any whitespace character. This includes spaces, tabs, form feeds, line breaks, and other whitespace characters as defined in Unicode.JavaScriptlet regex = /\s/; let str1 = "Hello World"; let str2 = "HelloWorld"; console.log(regex.test(st 2 min read JavaScript RegExp \r MetacharacterThe \r metacharacter in JavaScript regular expressions matches a carriage return character. A carriage return is a special control character (\r) with the ASCII code 13, often used to represent the end of a line in text files created on older operating systems (e.g., Windows uses \r\n for line break 2 min read JavaScript | RegExp \uxxxx MetacharacterThe RegExp \uxxxx Metacharacter in JavaScript is used to find the unicode character specified by a hexadecimal number xxxx. If match is found it returns the word else it returns NULL. Syntax: /\uxxxx/ or new RegExp("\\uxxxx") Syntax with modifiers: /\uxxxx/g or new RegExp("\\uxxxx", "g") Example 1: 2 min read JavaScript RegExp \W MetacharacterThe \W metacharacter in JavaScript regular expressions matches any character that is not a word character. A word character is defined as:Any alphanumeric character (a-z, A-Z, 0-9)The underscore (_)Essentially, \W matches anything that is not a letter, digit, or underscore.JavaScriptlet regex = /\W/ 2 min read JavaScript RegExp \w MetacharacterThe \w metacharacter in JavaScript regular expressions matches any word character. A word character is defined as:Any alphanumeric character (letters a-z, A-Z, numbers 0-9)The underscore character (_)It does not match spaces, punctuation, or other non-alphanumeric characters.JavaScriptlet regex = /\ 2 min read JavaScript | RegExp \xxx MetacharacterThe RegExp \xxx Metacharacter in JavaScript is used to find the character specified by an octal number xxx. If the match is found it returns the character else it returns NULL. Syntax: /\xxx/ or new RegExp("\\xxx") Syntax with modifiers: /\xxx/g or new RegExp("\\xxx", "g") Example 1: This example re 2 min read JavaScript RegExp \0 MetacharacterThe RegExp \0 Metacharacter in JavaScript is used to find the NULL character. If it is found it returns the position else it returns -1.JavaScriptlet str = "Geeksfo\0rGeeks@_123_$"; let regex = /\0/; let match = str.search(regex); if (match == -1) { console.log("No Null characters present. "); } els 2 min read Like