JavaScript RegExp (x|y) Alternation

Beginner
6 min read
Updated: Oct 2026
3 examples
Live preview

What Is (x|y)?

(x|y) is alternation (logical OR for patterns). The engine tries to match x; if that fails at the current position, it tries y. Parentheses group the branches so | applies to whole sub-patterns, not just one character.

Remember
/(cat|dog)/   → "cat" OR "dog"
/(https|http)/ → "https" OR "http"
/(red|green|blue)/ → any of three colors

/[xy]/        → one character: x OR y (class)
/(x|y)/       → sub-pattern x OR sub-pattern y

"I like cats".match(/(cat|dog)/)  → ["cat", "cat"]
UsePrefer
Match one of several words / strings/(cat|dog|bird)/
Match one of several single characters/[abc]/ (simpler)
Group without capturing/(?:cat|dog)/

How to Use (x|y)

List alternatives with | inside parentheses, then use test, match, or replace.

  1. Write /(optionA|optionB)/ (add more branches with more |).
  2. Use test() to check if either alternative appears.
  3. Use match() with g to collect every hit.
  4. Read capture group 1 when you need which branch matched.
PieceRequired?Role
|YesSeparates alternative branches
( … )UsuallyGroups branches; also captures by default
(?: … )OptionalNon-capturing group (grouping only)
Flag gOptionalFind every match in the string

Pseudocode

Pseudocode
pattern = (x | y)

at current position in text:
    try match x
    if x succeeds → success (branch x)
    else try match y
    if y succeeds → success (branch y)
    else → fail at this position

// engine may advance and retry later in the string

Cheat Sheet

Keep these facts handy while writing OR patterns.

TopicDetail
Syntax/(x|y)/
MeaningMatch sub-pattern x or sub-pattern y
vs class[xy] = one character; (x|y) = full patterns
Many options/(a|b|c|d)/
Capturematch[1] holds the branch that matched
Non-capture/(?:x|y)/
StandardCore regex (ES3+) — universal support

Live Preview

Pick a sample string and see matches of /(cat|dog)/g.

Browser demo of /(cat|dog)/g — same idea as the examples below.

Result
text = "I like cats"
text.match(/(cat|dog)/g)
→ ["cat"]

/* "cat" branch succeeds inside "cats" */

JavaScript Examples

Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.

Example 1 — Check Either Word with test()

Return true if the string contains cat or dog.

JavaScript
const pet = /(cat|dog)/;

console.log(pet.test("I like cats"));  // true
console.log(pet.test("dog park"));     // true
console.log(pet.test("bird house"));   // false
Try It Yourself

How It Works

  1. Two branches. (cat|dog) means try cat, else try dog.
  2. Substring OK. "cats" still contains cat → true.
  3. Second branch. "dog park" fails cat, then matches dog.
  4. Neither. "bird" matches no branch → false.

Example 2 — Collect Alternatives with match()

Use the global flag to list every cat or dog occurrence.

JavaScript
const text = "cat and dog";

console.log(text.match(/(cat|dog)/g));       // ["cat", "dog"]
console.log("catalog".match(/(cat|dog)/g));  // ["cat"]
console.log("bird".match(/(cat|dog)/g));     // null
Try It Yourself

How It Works

  1. Global scan. /g finds each separate match left to right.
  2. Both words. First cat, later dog → two results.
  3. Prefix match. "catalog" matches the cat branch at the start.
  4. No hit. No branch fits → null.

Example 3 — Capture Branch & Replace

Read which alternative matched, then replace every hit with one word.

JavaScript
const text = "See cat or dog";
const m = text.match(/(cat|dog)/);

console.log(m[0]);                         // "cat"
console.log(m[1]);                         // "cat"  (group 1)
console.log(text.replace(/(cat|dog)/g, "pet")); // "See pet or pet"
Try It Yourself

How It Works

  1. First match only. Without g, match returns the first hit plus groups.
  2. Full match. m[0] is the whole matched text ("cat").
  3. Group 1. Parentheses capture the winning branch — also "cat" here.
  4. Global replace. Every cat or dog becomes "pet".

Edge Cases & Pitfalls

Check these before relying on (x|y) in real projects.

order

Branch order can matter

Left branch is tried first. If a short option is a prefix of a longer one, put the longer option first when you need the full word: (catalog|cat).

vs

(x|y) vs [xy]

Use a character class for one-of-several characters. Use alternation for multi-character options like words or file extensions.

group

Parentheses capture by default

Use (?:x|y) when you only need grouping for precedence and do not want an extra capture group.

scope

Pipe has low precedence

Without parentheses, cat|dog still works as two alternatives for the whole pattern. Group when the OR should cover only part of a larger expression: /^(cat|dog)$/.

Browser & Runtime Support

Alternation with (x|y) is core JavaScript regular-expression syntax (ES3+) and works everywhere.

✓ Baseline · ES3+

RegExp (x|y)

Supported in all evergreen browsers, Internet Explorer, and every current Node.js / Deno / Bun release.

100% Universal support
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 4+ · Legacy environments
Full support
Opera All modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
(x|y) Universal

Bottom line: Safe everywhere. Use (x|y) for multi-character OR; use [xy] when each option is a single character.

Performance Notes

ApproachCostBest for
/(x|y)/.test(s)O(n)Quick “either option?” check
s.match(/(x|y)/g)O(n)List every alternative hit
s.replace(/(x|y)/g, r)O(n)Normalize every match

Simple alternation is linear for these patterns. Prefer test for yes/no checks. Very large OR lists can get slower — keep branches short when you can.

Key Takeaways

  • Role: (x|y) matches sub-pattern x or sub-pattern y.
  • vs class: Prefer [abc] for single characters; use | for words and longer pieces.
  • Capture: Parentheses store the winning branch in group 1; use (?:…) to skip capture.
  • Order: Left branch wins first — put longer options first when they overlap.

One line: (x|y) means “match this or that” — regex OR for whole sub-patterns, not just single characters.

Frequently Asked Questions

(x|y) is alternation: the engine tries pattern x first, and if that fails at that position, it tries pattern y. Parentheses group the alternatives so the pipe applies to whole sub-patterns.
[xy] matches exactly one character—either x or y. (x|y) matches full sub-patterns, which can be multiple characters like (cat|dog) or (https|http).
Yes. Alternation picks the first successful branch. "cat" matches at the start of "catalog", so the pattern succeeds even though "dog" was never needed.
Yes. Capturing parentheses store whichever alternative matched. Use a non-capturing group (?:x|y) when you only need grouping, not captured text.
Yes. Write (red|green|blue) or (jpg|jpeg|png|gif). Separate each branch with a pipe inside the group.
Yes when branches can overlap. Prefer longer or more specific options first if a shorter branch would “steal” the match—for example (catalog|cat) instead of (cat|catalog) when you need the full word.

Next: ignoreCase

Learn how the i flag makes patterns match regardless of letter case.

ignoreCase tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

13 people found this page helpful