DEV Community

Daniel Zotti
Daniel Zotti

Posted on

#LearnedToday: Named Capture Group

Yesterday I worked on a task for which the regular expressions were perfect.

Today I would like to share a feature that is supported since 2018 but that I have seen used very little: Named Capturing Group.

I really love this feature because it allows for neater and more readable regex.

const regex = /(?<day>\d+)\/(?<month>\d+)\/(?<year>\d+)/;

const { day, month, year } = regex.exec("16/04/1987").groups;

console.log({ day, month, year});
// {day: '16', month: '04', year: '1987'}
Enter fullscreen mode Exit fullscreen mode

I have created a simple example on stackblitz to hopefully make their use understood.

I also created an example on Regex101, a tool I always use to test regular expressions.

🔗 Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_capturing_group

ℹ Browser support: https://caniuse.com/mdn-javascript_regular_expressions_named_capturing_group

Top comments (0)