JavaScript `String.matchAll()`: Extract All Matches Easily

2 min read .

The String.matchAll() method in JavaScript is a powerful tool that returns an iterator of all matched results of a regular expression against a string, including capturing groups. This method is ideal for complex pattern matching, making it easy to retrieve multiple results with detailed information.

What is String.matchAll() in JavaScript?

String.matchAll() is a method introduced in ECMAScript 2020 that returns an iterator containing all matches of a regular expression in a string. Unlike String.match(), which only provides basic matching capabilities, matchAll() offers detailed match information, including capturing groups, making it incredibly useful for comprehensive pattern analysis.

Syntax:

string.matchAll(regex);
  • regex: A regular expression object with the global (g) flag enabled.

Why Use String.matchAll()?

  • Multiple Matches with Details: It captures all matches in a string, including capturing groups, providing more comprehensive information than String.match().
  • Iterator Format: Returns results as an iterator, allowing easy traversal and extraction of matches.
  • Detailed Matching: Includes information like matched text, indices, and capturing group details.

How to Use String.matchAll() in JavaScript

  1. Basic Usage of String.matchAll()
const text = "The quick brown fox jumps over the lazy dog.";
const regex = /(\w+)\s/g; // Matches words followed by space

const matches = text.matchAll(regex);

for (const match of matches) {
  console.log(match);
  // Outputs:
  // ["The ", "The", index: 0, input: "The quick brown fox jumps over the lazy dog.", groups: undefined]
  // ["quick ", "quick", index: 4, input: "The quick brown fox jumps over the lazy dog.", groups: undefined]
  // ...
}
  1. Extracting Matching Groups

matchAll() allows access to capturing groups, making it easy to extract specific portions of each match.

const text = "Order #123, Order #456, Order #789";
const regex = /Order #(\d+)/g; // Captures order numbers

const matches = text.matchAll(regex);

for (const match of matches) {
  console.log(`Found order number: ${match[1]}`);
  // Output:
  // Found order number: 123
  // Found order number: 456
  // Found order number: 789
}
  1. Converting matchAll() Iterator to Array

You can convert the iterator returned by matchAll() into an array using the spread operator or Array.from():

const text = "cat bat mat";
const regex = /\b(\w+)at\b/g;

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

console.log(matchesArray);
// Output:
// [
//   ["cat", "c", index: 0, input: "cat bat mat", groups: undefined],
//   ["bat", "b", index: 4, input: "cat bat mat", groups: undefined],
//   ["mat", "m", index: 8, input: "cat bat mat", groups: undefined]
// ]
  1. Using matchAll() with Named Capturing Groups

Named capturing groups make it easier to access specific parts of matches by their group names.

const text = "John: 123, Jane: 456";
const regex = /(?<name>\w+): (?<number>\d+)/g; // Named capturing groups

const matches = text.matchAll(regex);

for (const match of matches) {
  console.log(`Name: ${match.groups.name}, Number: ${match.groups.number}`);
  // Output:
  // Name: John, Number: 123
  // Name: Jane, Number: 456
}

Differences Between String.match() and String.matchAll()

  • String.match(): Returns an array of matches when using the global flag, but without detailed information on capturing groups.
  • String.matchAll(): Returns an iterator of match objects, each containing detailed information, including capturing groups, indices, and the matched string.

Performance Considerations

  • matchAll() is useful when detailed match information is needed, but it is slightly slower than match() due to its comprehensive output.
  • For simple pattern checks, match() might be more efficient.

Browser Compatibility

String.matchAll() is supported in modern browsers, including Chrome (version 73+), Firefox (version 67+), Safari (version 13+), and Edge (version 79+). It is not supported in Internet Explorer, so consider this if targeting older browsers.

Conclusion

JavaScript’s String.matchAll() method is a powerful tool for advanced pattern matching. By providing detailed information on every match and its capturing groups, matchAll() is ideal for complex string parsing and analysis tasks.

See Also

chevron-up