Get Every RegExp Match with `String.matchAll()`
1
min read .
Updated on
String.prototype.matchAll() returns an iterator containing every match of a global regular expression, including capturing groups and match indexes.
const text = 'Order #123, Order #456, Order #789';
const regex = /Order #(\d+)/g;
for (const match of text.matchAll(regex)) {
console.log(match[0], match[1], match.index);
}Named Capturing Groups
const text = 'John: 123, Jane: 456';
const regex = /(?<name>\w+): (?<number>\d+)/g;
for (const match of text.matchAll(regex)) {
console.log(match.groups.name, match.groups.number);
}Convert the Iterator to an Array
const matches = [...'cat bat mat'.matchAll(/\b(\w+)at\b/g)];This is convenient when you need map, filter, or other array operations, but iterating directly avoids storing all matches at once.
Global Regex Requirement
When you pass a RegExp, it must have the g flag. Without it, matchAll() throws a TypeError.
match() vs. matchAll()
With a global regex, match() returns only the matched strings and does not preserve capturing-group detail for every match. matchAll() gives you a full match object for each occurrence.
Conclusion
Use matchAll() when you need every occurrence plus captures, named groups, or positions. It replaces manual RegExp.exec() loops with a clearer iteration API.