Capture Groups in matchAll()
You'll learn how to extract all matches and their capture groups at once using matchAll().
When you need to find every occurrence of a pattern that includes capture groups, matchAll() is your best friend. Unlike match() with the global flag (which only returns full matches), matchAll() gives you an iterator containing complete match objects—including all capture groups—for every single match.
How matchAll() Works
Think of matchAll() as a conveyor belt delivering detailed match reports, one after another. Each "report" contains the full match and all captured substrings.
You call it on a string with a global regex (must have the g flag), and it returns an iterator. Loop through it with for...of or convert it to an array:
const text = "Contact: John (555-1234) or Jane (555-5678)";
const pattern = /(\w+) \((\d{3}-\d{4})\)/g;
for (const match of text.matchAll(pattern)) {
console.log(`Full match: ${match[0]}`);
console.log(`Name: ${match[1]}`);
console.log(`Phone: ${match[2]}`);
console.log('---');
}
// Full match: John (555-1234)
// Name: John
// Phone: 555-1234
// ---
// Full match: Jane (555-5678)
// Name: Jane
// Phone: 555-5678
Each iteration gives you an array-like object where match[0] is the entire match, match[1] is the first capture group, match[2] is the second, and so on.
Why It Matters
Without matchAll(), you'd need a loop with exec() to get the same information. matchAll() is cleaner and easier to iterate over when you need all matches with their groups intact.
Key Takeaway: Use matchAll() with a global regex to iterate over all matches and access their capture groups in one clean loop.