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:
- The full matched text.
- All captured parenthetical groups.
- The
indexwhere the match was found. - The original
inputstring. - Named capture groups (via the
groupsobject).
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()
match()with/g: Returns a plain array containing only the fully matched substrings, completely stripping out capturing groups and index metadata.matchAll()with/g: Returns an iterator yielding full match objects that contain the captured groups, index, and original input for every single match.
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
- Tokenizing and Parsing: Extracting structured tokens, attributes, or key-value pairs from raw strings.
- Accessing Capture Groups Globally: Retrieving specific sub-patterns across entire documents without losing parenthetical captures.
- Memory Efficiency: Iterating over large strings lazily one match at a time rather than allocating a large array in memory upfront.