Check whether a string matches a regex in JS

Learn check whether a string matches a regex in js with practical examples, diagrams, and best practices. Covers javascript, regex, match development techniques with visual explanations.

Mastering Regex Matching in JavaScript

Hero image for Check whether a string matches a regex in JS

Learn the various methods to check if a string matches a regular expression in JavaScript, from simple tests to capturing groups.

Regular expressions (regex) are powerful tools for pattern matching within strings. In JavaScript, there are several ways to determine if a string conforms to a specific regex pattern. This article will explore the primary methods available, including RegExp.prototype.test(), String.prototype.match(), and String.prototype.search(), along with their use cases and nuances.

The test() Method: Simple Boolean Check

The test() method of a RegExp object is the simplest way to check for a match. It returns true if the regex finds a match in the specified string, and false otherwise. This method is ideal when you only need a boolean answer and don't require details about the match itself.

const regex = /hello/;
const str1 = "hello world";
const str2 = "hi there";

console.log(regex.test(str1)); // true
console.log(regex.test(str2)); // false

const emailRegex = /^\S+@\S+\.\S+$/;
console.log(emailRegex.test("test@example.com")); // true
console.log(emailRegex.test("invalid-email"));    // false

Using RegExp.prototype.test() for a boolean match check.

The match() Method: Extracting Match Details

The match() method of a String object is more versatile than test(). It returns an array containing the match results, or null if no match is found. The structure of the returned array depends on whether the regex has the global flag (g).

When the regex does not have the global flag, match() returns an array similar to the result of RegExp.prototype.exec(). This array includes the full matched string, captured groups, the index of the match, the input string, and the groups object (for named capture groups).

const regex = /(\w+)\s(world)/;
const str = "hello world, welcome!";

const result = str.match(regex);

console.log(result); 
/*
[ 
  'hello world',
  'hello',
  'world',
  index: 0,
  input: 'hello world, welcome!',
  groups: undefined
]
*/
console.log(result[0]); // "hello world" (full match)
console.log(result[1]); // "hello" (first capturing group)
console.log(result[2]); // "world" (second capturing group)
console.log(result.index); // 0

Using String.prototype.match() without the global flag to get detailed match information.

When the regex does have the global flag (g), match() returns an array containing all full matches found in the string. It does not include capturing groups in this scenario. If no matches are found, it returns null.

const regexGlobal = /\b\w+\b/g; // Match all words
const str = "apple banana cherry";

const allWords = str.match(regexGlobal);
console.log(allWords); // ["apple", "banana", "cherry"]

const noMatch = "123 456".match(/abc/g);
console.log(noMatch); // null

Using String.prototype.match() with the global flag to find all occurrences.

The search() Method: Finding the First Match Index

The search() method of a String object executes a search for a match between a regular expression and this String object. It returns the index of the first match found, or -1 if no match is found. This method is useful when you need to know where the first match occurs, but not the match content itself.

const regex = /world/;
const str1 = "hello world";
const str2 = "hi there";

console.log(str1.search(regex)); // 6 (index of 'w' in 'world')
console.log(str2.search(regex)); // -1

const caseInsensitiveRegex = /apple/i;
console.log("I love Apples.".search(caseInsensitiveRegex)); // 7

Using String.prototype.search() to find the index of the first match.

Choosing the Right Method

The choice of method depends on your specific needs. Here's a quick guide:

flowchart TD
    A[Start: Need to check regex match?] --> B{Only boolean result needed?}
    B -- Yes --> C[Use `RegExp.prototype.test()`]
    B -- No --> D{Need match content or groups?}
    D -- Yes --> E{Need all matches (full strings)?}
    E -- Yes --> F[Use `String.prototype.match()` with `/g` flag]
    E -- No --> G{Need first match details (groups, index)?}
    G -- Yes --> H[Use `String.prototype.match()` without `/g` flag]
    G -- No --> I{Only need index of first match?}
    I -- Yes --> J[Use `String.prototype.search()`]
    I -- No --> K[Consider `RegExp.prototype.exec()` for iterative matching with groups]
    C --> L[End]
    F --> L
    H --> L
    J --> L
    K --> L

Decision flow for choosing the appropriate JavaScript regex matching method.

For more advanced scenarios, especially when you need to iterate over all matches and capture groups, RegExp.prototype.exec() is the method of choice. It returns an array for each match (similar to match() without g) and updates the lastIndex property of the regex, allowing you to call it repeatedly to find subsequent matches.

const regex = /\b(\w+)\b/g;
const str = "one two three";
let match;

while ((match = regex.exec(str)) !== null) {
  console.log(`Found '${match[0]}' at index ${match.index}. Next search starts at ${regex.lastIndex}`);
  // Expected output:
  // Found 'one' at index 0. Next search starts at 3
  // Found 'two' at index 4. Next search starts at 7
  // Found 'three' at index 8. Next search starts at 13
}

Iterating over matches and capturing groups using RegExp.prototype.exec().