DEV Community

Bonnie DiPasquale
Bonnie DiPasquale

Posted on

Regular expression named capture groups

I saw this tweet today and wanted to dig a little deeper into the destructuring assignment...

Addy Osmani tweet on regular expression capture groups

The capture group is composed by putting everything in the group between parens, and naming it with ?<name>

so year alone would like this:

const year = /(?<year>\d{4})/

The destructuring part of the tweet and Axel's follow-up, I found confusing. How can I destructure it as both an object and array?

const [match, year, month, day] = re.exec('2021-03-04');

Looking at the object keys helped clear things up:

console.log("'re' object keys:",Object.keys(re.exec('2021-03-04')));

gives me:

["0","1","2","3","index","input","groups"]
Enter fullscreen mode Exit fullscreen mode

Code can be found here:
Codepen

Top comments (0)