Last Updated : 11 Jul, 2025
The (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.
JavaScript
let regex = /(cat|dog)/g;
let str = "I have a cat and a dog.";
let matches = str.match(regex);
console.log(matches);
The pattern (cat|dog) matches either cat or dog in the string.
Syntax:/(x|y)/
let regex = /(red|blue)/g;
let str = "The flag is red and blue.";
let matches = str.match(regex);
console.log(matches);
Here, (red|blue) matches either "red" or "blue".
2. Matching Single Characters JavaScript
let regex = /(a|e|i|o|u)/g;
// Matches any vowel
let str = "hello world";
let matches = str.match(regex);
console.log(matches);
The pattern (a|e|i|o|u) matches any vowel in the string.
3. Using Alternation with Complex Patterns JavaScript
let regex = /(Mr\.|Mrs\.|Ms\.)\s[A-Z][a-z]+/g;
let str = "Mr. Smith and Mrs. Johnson are here.";
let matches = str.match(regex);
console.log(matches);
[ 'Mr. Smith', 'Mrs. Johnson' ]
The (Mr\.|Mrs\.|Ms\.) pattern matches formal titles followed by a capitalized last name.
4. Validating Input with Multiple Options JavaScript
let regex = /^(yes|no|maybe)$/;
let input = "yes";
if (regex.test(input)) {
console.log("Valid input.");
} else {
console.log("Invalid input.");
}
Here, the pattern ^(yes|no|maybe)$ ensures the input is either "yes", "no", or "maybe".
5. Matching File Extensions JavaScript
let regex = /\.(jpg|png|gif)$/;
let filename = "picture.png";
if (regex.test(filename)) {
console.log("Valid image file.");
} else {
console.log("Invalid file format.");
}
The (jpg|png|gif) pattern matches specific file extensions.
Common Patterns Using (x|y)/(apple|banana|cherry)/g
/(Dr\.|Mr\.|Ms\.)\s[A-Z][a-z]+/
/(123|456)/g
/colou?r/ // Matches "color" or "colour"Why Use (x|y)?
The (x|y) expression is a powerful tool for defining alternatives in JavaScript regular expressions, making it invaluable for text validation, parsing, and extraction.
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