SyntaxStudy
Sign Up
JavaScript String matchAll() for All Matches
JavaScript Intermediate 5 min read

String matchAll() for All Matches

matchAll()

matchAll() returns an iterator of all matches, including full match details and capture groups. Requires the g flag.

Example
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)];
Pro Tip

matchAll() is cleaner than exec() in a loop because it does not mutate the regex object's lastIndex.