How do you test whether a string matches a regular expression in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you test whether a string matches a regular expression in JavaScript?

message-square
0

To test whether a string matches a regular expression in JavaScript, use regex.test(str) when you only need a boolean (true or false), or str.match(regex) / str.matchAll(regex) when you also need captured groups or match positions. Watch out for the global (g) or sticky (y) flag with .test(), because stateful regexes advance regex.lastIndex across calls and can skip or misreport matches unless reset or created fresh.


1. Boolean Match Testing with RegExp.prototype.test()

Call regex.test(str) to check whether str satisfies regex and get a straightforward boolean return value, while avoiding stateful lastIndex bugs when a regex includes the g or y flag:

// Test whether a string matches a regex without stateful lastIndex drift
function matchesPattern(input, pattern) {
  if (typeof input !== "string") {
    throw new TypeError("Expected input to be a string.");
  }

  if (!(pattern instanceof RegExp)) {
    throw new TypeError("Expected pattern to be a RegExp instance.");
  }

  const flags = pattern.flags.replace(/[gy]/g, "");
  const statelessRegex = new RegExp(pattern.source, flags);
  return statelessRegex.test(input);
}

// Example usage:
const skuPattern = /^[A-Z]{2,4}-\d{4}$/;
console.log(matchesPattern("ORD-2026", skuPattern));   // true
console.log(matchesPattern("ord-2026", skuPattern));   // false
console.log(matchesPattern("INV-12", skuPattern));     // false
  • Anchor for full-string checks: Use ^ and $ (or \A / \z concepts in patterns) when validating an entire string rather than a substring.
  • Beware global/sticky lastIndex: Calling /foo/g.test("foo") twice in a row returns true first and false second because lastIndex moves to 3 after the first match.

2. Extracting Match Data and Capture Groups with .match()

When you need more than true or false—such as matched text, capture groups, or the starting index—use str.match(regex), which returns a match array on success or null when nothing matches:

// Parse structured log prefix and return capture groups or null
function parseLogPrefix(line) {
  if (typeof line !== "string") {
    throw new TypeError("Expected line to be a string.");
  }

  const logRegex = /^\[(INFO|WARN|ERROR)\]\s+(.+)$/;
  const match = line.match(logRegex);
  if (!match) {
    return null;
  }

  return {
    level: match[1],
    message: match[2],
    index: match.index
  };
}

// Example usage:
console.log(parseLogPrefix("[ERROR] Connection timed out")); // { level: "ERROR", message: "Connection timed out", index: 0 }
console.log(parseLogPrefix("Plain text line"));              // null
  • Always handle null: .match() returns null on no match, so guard before reading match[1] or match.index.
  • g flag changes return shape: Without g, .match() includes capture groups and .index; with g, it returns an array of full matched strings without individual capture groups.

3. Finding Every Match and Capture Group with .matchAll()

For repeated occurrences across a string with full capture details on every hit, use str.matchAll(regex) (which requires the g flag) and iterate over the returned iterator or convert it with Array.from() or [...iterator]:

// Collect all @username mentions with their character offsets
function findMentions(text) {
  if (typeof text !== "string") {
    throw new TypeError("Expected text to be a string.");
  }

  const mentionRegex = /@([a-zA-Z0-9_]{1,30})/g;
  return Array.from(text.matchAll(mentionRegex), (match) => ({
    handle: match[1],
    raw: match[0],
    index: match.index
  }));
}

// Example usage:
const note = "Ping @dev_ops and @qa_lead before deploy.";
console.log(findMentions(note));
// [{ handle: "dev_ops", raw: "@dev_ops", index: 5 }, { handle: "qa_lead", raw: "@qa_lead", index: 21 }]
  • Requires g flag: Passing a regex without g to .matchAll() throws a TypeError.
  • Non-mutating on source string: Like .test() and .match(), .matchAll() never modifies the original string.

TL;DR: Use regex.test(str) for boolean checks (avoiding reusable g/y lastIndex pitfalls), str.match(regex) for a single match/groups (checking for null), and str.matchAll(regex) with the g flag for all matches and capture groups.