JavaScript String matchAll Method Explained

The matchAll() method in JavaScript provides a robust and memory-efficient way to retrieve all regular expression matches along with their capturing groups from a string. Introduced in ECMAScript 2020 (ES11), it resolves a long-standing limitation of the standard match() method, which omits capturing groups when used with the global (/g) flag. This article explains the purpose of matchAll(), how it works under the hood, and how to use it effectively in modern JavaScript applications.

The Purpose of matchAll()

The primary purpose of String.prototype.matchAll() is to iterate over all matches of a regular expression against a string while preserving full match details, including:

Before matchAll(), developers had to use a while loop combined with RegExp.prototype.exec() to extract multiple matches alongside capturing groups. The matchAll() method standardizes and simplifies this pattern into a single built-in call.

Key Differences: match() vs. matchAll()

Syntax and Requirements

string.matchAll(regexp)

The regular expression passed to matchAll() must have the global flag (g). If the regex does not contain /g, a TypeError is thrown to prevent infinite loops during iteration.

How to Use matchAll()

Because matchAll() returns an iterator (specifically, a RegExp String Iterator), the results are evaluated lazily. You can consume the results using a for...of loop, the spread operator (...), or Array.from().

Example: Extracting Data with Capturing Groups

Consider an example where you need to parse key-value pairs from a configuration string:

const text = "name: John Doe; age: 30; role: Developer;";
const regex = /(\w+):\s*([^;]+);/g;

// Using matchAll with a for...of loop
for (const match of text.matchAll(regex)) {
  const [fullMatch, key, value] = match;
  console.log(`Found: ${key} = ${value} (at index ${match.index})`);
}

Example: Converting to an Array

If you need the results as an array of match objects, you can spread the iterator:

const results = [...text.matchAll(regex)];

console.log(results[0][1]); // "name"
console.log(results[0][2]); // "John Doe"

Summary of Use Cases