Example 1 — All Matches with Capturing Groups
Spread matchAll() to get every hit with its groups.
const regexp = /t(e)(st(\d?))/g;
const str = "test1test2";
const array = [...str.matchAll(regexp)];
console.log(array[0][0], array[0][1], array[0][3]); // test1 e 1
console.log(array[1][0], array[1][1], array[1][3]); // test2 e 2 How It Works
- Build a global regex.
/t(e)(st(\d?))/ghas three capturing groups and the requiredgflag. - Scan the string.
matchAllfinds"test1"then"test2". - Read each hit. Index
0is the full match; later indexes are groups ("e","st1","1"). - Spread to an array.
[...]collects both match arrays so you can index them.

