Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk4 min

Using Regular Expressions in a JavaScript switch…case Statement

JavaScript switch cases use strict equality, so case /pattern/ does not match a string. Use test(), switch(true), or match first and switch on the result.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Short answer: You cannot make case /pattern/ test a string with that regular expression. JavaScript evaluates each case expression and compares its value with the switch expression using strict equality (===). A string and a RegExp object are different values. Use if/else if with RegExp.prototype.test(), use switch (true) for an ordered list of predicates, or perform the match first and switch on a captured or classified value.

Why case /pattern/ does not match text

Consider this code:

const input = "error: disk full";

switch (input) {
  case /error/:
    console.log("error");
    break;
  default:
    console.log("no match");
}

The regular expression is evaluated as a RegExp object. The switch then asks whether input === /error/; it does not call the expression’s matcher. Because the left side is a string and the right side is an object, the case is skipped. Even two separately created expressions such as /error/ and /error/ are distinct object references.

This is the practical meaning behind the older explanation that a switch evaluates the switch expression against each case expression: it compares values, rather than interpreting a case as a pattern-matching operation.

Use if/else if for ordinary regex predicates

For a short, ordered list of regular-expression checks, this is usually the clearest solution:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function classify(input) {
  if (/^error:/i.test(input)) return "error";
  if (/^warn:/i.test(input)) return "warning";
  return "other";
}

test() returns a boolean: true when the expression matches and false otherwise. The ^ anchor makes the prefix requirement explicit, while the i flag makes the check case-insensitive. Without the anchor, /error:/ would also match text such as "previous error: disk full".

Use switch (true) when you want switch-style layout

Each case below evaluates to a boolean. A matching case therefore equals the switch value true:

function classify(input) {
  switch (true) {
    case /^error:/i.test(input):
      return "error";
    case /^warn:/i.test(input):
      return "warning";
    default:
      return "other";
  }
}

This keeps the visual structure of a switch while allowing arbitrary conditions. It is still an ordered decision list: JavaScript selects the first case whose expression is strictly equal to true.

Put specific patterns before broad patterns

Ordering is part of the logic. A broad expression can prevent a later, more specific one from running:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
switch (true) {
  case /error/i.test(input):
    return "general error";
  case /^error: auth/i.test(input):
    return "authentication error"; // unreachable for matching input
}

Reverse those cases when the authentication-specific result is preferred.

Match first, then switch on the result

When a branch needs captured text or a format classification, run the regular expression once and switch on a value produced by that match:

function colorFormat(s) {
  const re = /^((#[0-9a-f]{3,6})|([a-z]+)|(rgb([^)]+)))$/i;
  const m = re.exec(s);
  if (!m) return false;

  switch (m[1]) {
    case m[2]: return "hex code";
    case m[3]: return "string name";
    case m[4]: return "rgb code";
    default: return false;
  }
}

Here exec() returns the match array and capture groups. The switch handles ordinary values rather than trying to make the case label perform another regex search. String methods such as match() can serve the same purpose when their return shape fits the parser.

Switch on an explicit classification when that is easier to read

For more complex parsing, derive a named category first:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function classifyCommand(input) {
  const match = /^(error|warn):s*(.*)$/i.exec(input);
  if (!match) return "other";

  const level = match[1].toLowerCase();
  switch (level) {
    case "error":
      return { type: "error", message: match[2] };
    case "warn":
      return { type: "warning", message: match[2] };
  }
}

This separates pattern recognition from exact-value routing, which is often easier to extend and test.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose the right technique

Technique Best fit Captured data Main caution
if/else if with test() A few ordered regex predicates No; call exec() or match() separately Long chains can become difficult to scan
switch (true) A deliberately ordered list of conditions Not from test() alone Case order determines the result
exec()/match(), then switch Branches that need captures or a format category Yes Define and document the capture layout
Exact token switch with regex validation inside a branch Commands with discrete names plus per-command syntax Yes, when validated in the branch Do not confuse exact token routing with pattern routing
Ordered rule table Many patterns maintained as data Yes, if each rule stores its match result Make precedence explicit

Regular-expression details that affect these patterns

Be careful with global and sticky expressions

Regular expressions carrying the g (global) or y (sticky) flag retain a lastIndex position. Repeated calls to test() on the same object can therefore alternate between matches and misses as the starting position changes. For independent boolean checks, omit those flags or reset lastIndex deliberately:

const re = /error/g;
re.lastIndex = 0;
const first = re.test("error");
re.lastIndex = 0;
const again = re.test("error");

Anchor the match to the intended scope

  • Use ^ when text must start with a marker, such as ^error:.
  • Use $ when the text must end with a marker.
  • Use both when the complete input must conform to one format.
  • Leave the expression unanchored only when a match anywhere in the string is intentional.

Use captures when the branch needs the matched text

test() answers only whether a match exists. Use exec() or match() when you need the complete match, capture groups, or positions for subsequent logic.

Common mistakes and fixes

  • Putting a regex directly in a case: replace it with test(), switch (true), or a preliminary match.
  • Expecting regex literals to compare by source: regular-expression objects are not equal merely because their text is identical.
  • Using an unanchored pattern for a prefix check: add ^ (and, when appropriate, $).
  • Repeating a stateful regex in conditions: avoid unintended g/y state or manage lastIndex.
  • Ordering a broad case first: move specific predicates above general ones.
  • Using test() when captures are required: switch to exec() or match() before branching.

Bottom line

A JavaScript switch statement is an exact-value dispatcher, not a regular-expression matcher. For most pattern checks, use if/else if with test(). Use switch (true) when an ordered predicate list benefits from switch syntax, and match first with exec() or match() when the branch needs captured data.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.