brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: matchAll() with named groups pulls every match out of a string

Web-Development
~/tips/tip-javascript-string-matchall-named-groups

const re = /(?<year>\d{4})-(?<month>\d{2})/g;

Returns every regex match including capture groups, readable with named groups.

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()

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link