matchAll()
matchAll() returns an iterator of all matches, including full match details and capture groups. Requires the g flag.
matchAll() returns an iterator of all matches, including full match details and capture groups. Requires the g flag.
const text = "Call 555-1234 or 555-5678 for support";
const phone = /(\d{3})-(\d{4})/g;
for (const match of text.matchAll(phone)) {
console.log(match[0]); // "555-1234"
console.log(match[1]); // "555"
console.log(match[2]); // "1234"
console.log(match.index); // position in string
}
// Collect all into array
const all = [...text.matchAll(phone)];
matchAll() is cleaner than exec() in a loop because it does not mutate the regex object's lastIndex.
More in JavaScript