matchAll(): Iterating Over All Matches
You'll learn how to use matchAll() to retrieve every match of a regular expression, including capture groups, in a convenient iterable format.
What matchAll() Does
While match() gives you all matches when using a global flag, it doesn't return capture groups for each match. That's where matchAll() comes in. It returns an iterator that lets you loop through every match, with full details including capture groups for each one.
Think of matchAll() like getting a detailed report for each item found, rather than just a simple list. If you're searching for phone numbers with area codes, matchAll() gives you each complete phone number and its area code separately.
Basic Usage
const text = "Call me at 555-1234 or 555-5678";
const regex = /(\d{3})-(\d{4})/g; // Note: must use 'g' flag
const matches = text.matchAll(regex);
for (const match of matches) {
console.log(`Full match: ${match[0]}`);
console.log(`Area code: ${match[1]}`);
console.log(`Number: ${match[2]}`);
}
// Full match: 555-1234
// Area code: 555
// Number: 1234
// Full match: 555-5678
// Area code: 555
// Number: 5678
Important Details
- Requires the global flag (
g): Your regex must include/gor it throws an error - Returns an iterator: You can loop over it with
for...ofor convert it to an array - Each match is an array: Index
[0]is the full match,[1],[2], etc. are capture groups - One-time use: Once iterated, the iterator is exhausted
Key Takeaway: matchAll() gives you an iterator of detailed match objects, perfect when you need to examine capture groups for every occurrence of a pattern.