Regex in JavaScript has an old trap: str.match(/re/g) returns the matches but drops the capture groups. matchAll() keeps them, and named groups make the result readable. My advice is to name the groups, because m.groups.year reads better than m[1].
Give the pattern named groups with (?<name>...) and the g flag, then loop over the results:
const re = /(?<year>\d{4})-(?<month>\d{2})/g;
const text = "2020-01 and 2021-12";
for (const m of text.matchAll(re)) {
console.log(m.groups.year, m.groups.month, m.index);
}
// 2020 01 0
// 2021 12 12
Each item looks like the result of exec(): the full match, the groups, the index and the input. To get a plain array, spread it or use Array.from():
const all = [...text.matchAll(re)].map((m) => m.groups);
// [{ year: "2020", month: "01" }, { year: "2021", month: "12" }]
Two caveats. The regex needs the g flag or matchAll() throws a TypeError. And the return value is an iterator that can only be used once: after a for...of it is empty, so turn it into an array first when you need it twice.
The old way was a while ((m = re.exec(text))) loop, which also depends on the regex’s lastIndex state and is easy to get stuck in. matchAll() works on a copy of the regex, so your original is not changed.
It is available in all major browsers since January 2020.
Further reading: MDN: String.prototype.matchAll()