Course contentsShow
← JavaScript
Lesson 1670 of 2,72336. Regular ExpressionsFree lesson

The Pipe Operator for Alternation

Matching one pattern or another with | to create either/or conditions.

The Pipe Operator for Alternation

You'll learn how to match one pattern or another using the | operator in regular expressions.

What Is the Pipe Operator?

The pipe operator (|) in regular expressions works like the word "or" in everyday language. It lets you specify multiple alternative patterns, and the regex will match if any one of those patterns is found. Think of it as offering your regex engine multiple choices: "Match this pattern OR that pattern OR that other pattern."

How It Works

When you write cat|dog, you're telling the regex: "Match either 'cat' or 'dog'." The engine tries to match from left to right and stops as soon as it finds a successful match.

const pattern = /cat|dog/;

console.log(pattern.test("I have a cat"));  // true
console.log(pattern.test("I have a dog"));  // true
console.log(pattern.test("I have a bird")); // false

You can chain multiple alternatives:

const colorPattern = /red|blue|green/;

console.log(colorPattern.test("My car is red"));   // true
console.log(colorPattern.test("The sky is blue")); // true
console.log(colorPattern.test("Her shirt is yellow")); // false

Order Matters

The regex engine tests alternatives from left to right. Once it finds a match, it stops. This usually doesn't matter for completely different words, but keep it in mind for overlapping patterns.

const pattern = /cat|category/;
console.log("category".match(pattern)); // matches "cat" only

Key Takeaway: The pipe operator (|) creates "or" conditions in regular expressions, allowing you to match any one of several alternative patterns.