JavaScript Regex (OR)
JavaScript regular expressions (RegEx) offer powerful capabilities for pattern matching within strings. One of the key components of RegEx is the OR operator,
JavaScript regular expressions (RegEx) offer powerful capabilities for pattern matching within strings. One of the key components of RegEx is the OR operator, represented by the vertical bar (|). This operator allows for the inclusion of multiple patterns within a single regular expression, enabling versatile and efficient string searches and manipulations. In this comprehensive guide, we will explore the usage of the OR operator in JavaScript RegEx, complete with practical examples to enhance your understanding.
Understanding the OR Operator (|) in RegEx
The OR operator in regular expressions allows you to specify multiple alternatives for a match. It is particularly useful when you need to match one pattern out of several possible patterns.
Basic Usage of the OR Operator
The syntax for the OR operator is straightforward. It involves placing the | symbol between the patterns you want to match.
In this example, the pattern /cat|dog/ matches both "cat" and "dog" in the given strings.
Alternation Precedence: Why You Almost Always Need Parentheses
This is the single biggest gotcha with |. The OR operator has very low precedence — lower than any other regex operator. That means | splits the entire expression into alternatives, all the way to the surrounding delimiters or the nearest enclosing parentheses.
So /cat|concatenate/ does not mean "cat optionally followed by concatenate". It means: match the whole pattern cat, OR match the whole pattern concatenate. Likewise, /^cat|dog$/ reads as (^cat)|(dog$) — "starts with cat" OR "ends with dog" — which is rarely what people intend.
To scope alternation to just part of a pattern, wrap the alternatives in parentheses.
Anchoring the whole thing with ^ and $ is a common companion to grouped alternation — see Anchors: string start and end.
The Order Matters: First Match Wins
The regex engine tries alternatives left to right and stops at the first one that succeeds at the current position. It does not look for the longest match — just the first one. This means the order of your alternatives is significant.
Rule of thumb: list the longer or more specific alternatives before the shorter ones they share a prefix with.
Grouping with Parentheses
Parentheses () group parts of a regular expression so quantifiers and other operators apply to the whole group, and they also capture the matched text for later use (see Capturing Groups). This is essential when you want the OR to cover only a fragment of a larger pattern.
Here, the s? quantifier applies to the whole (cat|dog) group, so the pattern matches "cat", "cats", "dog", and "dogs". The ? quantifier and friends are covered in Quantifiers +, * and {n}.
Practical Examples
Matching Different File Extensions
Suppose you need to validate file names with different extensions such as .jpg, .png, or .gif.
In this example, the pattern /\.(jpg|png|gif)$/ matches file names ending with ".jpg", ".png", or ".gif". The leading \. matches a literal dot, the group (jpg|png|gif) is the alternation, and $ anchors the match to the end of the string.
Validating Phone Numbers
Consider a scenario where you need to validate different formats of phone numbers.
Reading the pattern /(\+\d{1,2}\s?)?(\(\d{3}\)|\d{3})[-.\s]?\d{3}[-.\s]?\d{4}/ piece by piece:
(\+\d{1,2}\s?)?— an optional country code: a+, one or two digits, then an optional space. The trailing?makes the whole group optional.(\(\d{3}\)|\d{3})— the alternation: either three digits in parentheses(123)or three bare digits123. Note that\(and\)are literal parentheses, while the outer unescaped()does the grouping.[-.\s]?— an optional separator: a hyphen, a dot, or whitespace. (These are character classes.)\d{3}— three digits.[-.\s]?— another optional separator.\d{4}— the final four digits.
Plain Alternation vs. Optional Subpatterns
A common confusion is treating color|colour as if the u were optional. It is not — this is plain alternation between two complete words.
When the alternatives differ by only a single character (or a short run), the idiomatic and more efficient approach is a quantified optional subpattern, not alternation. The ? quantifier makes the preceding u optional:
Reach for alternation (|) when the choices are genuinely distinct strings (cat|dog); reach for ? when one form is the other plus an optional fragment (colou?r).
Combining the OR Operator with Other Metacharacters
The power of the OR operator is enhanced when combined with other regular expression metacharacters, such as * (zero or more), + (one or more), ? (zero or one), and {} (exactly n times).
Example with Quantifiers
The pattern /\b(cat|dog)s?\b/ matches "cat", "cats", "dog", and "dogs" as whole words, using the word boundary metacharacter \b.
Advanced Example with Multiple Conditions
The two date formats below — D-M-YYYY and YYYY-M-D — both use the same separators and digit counts, so the regex cannot tell day-month order apart by shape alone. What it can distinguish is where the four-digit year sits: at the end for one format, at the start for the other.
This pattern matches dates in both the day-first (12-31-2023, 31-12-2023) and year-first (2023-12-31) formats. Note that 31-12-2023 does match — it is a perfectly valid \d{1,2}-\d{1,2}-\d{4} string, so the first alternative accepts it.
A subtle but important detail: because | has the lowest precedence, the ^ binds only to the first alternative and $ only to the second. To anchor both alternatives, group them:
Using Alternation with match(), matchAll() and replace()
test() only tells you whether a pattern matched. To extract or transform the matched text, combine alternation with capturing groups and the string methods match(), matchAll(), and replace().
match() (without the g flag) returns the first match plus each captured group:
With the g flag, match() returns every match as an array, and matchAll() gives you an iterator of full match objects:
replace() lets you rewrite each alternative. Here we normalize British and American spellings to one form:
Conclusion
Mastering the OR operator in JavaScript regular expressions opens up a wide range of possibilities for efficient and versatile pattern matching. By understanding how to use the OR operator in combination with other RegEx features, you can create powerful and flexible patterns to handle complex string searches and manipulations.
Practice
Before submitting, reason through each option. Remember that every option below is valid regex syntax — the question is what each one actually matches:
/cat|dog/— plain alternation using|; matches "cat" or "dog" anywhere in a string. Correct./(cat|dog)/— same alternation wrapped in a capturing group; the group does not change what is matched, only that the match is captured. Correct./cat|dogs/— valid, but the second alternative is "dogs" (with ans), so it never matches the bare word "dog". Incorrect for this question./cat||dog/— the empty alternative between the two|symbols matches an empty string, so this matches almost anything, including strings that contain neither word. Incorrect./(cat|dog)s/— the requiredsafter the group means this matches "cats" or "dogs", not "cat" or "dog". Incorrect./cat|do g/— the space is a literal character, so the second alternative is "do g" (with a space), not "dog". Incorrect.