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

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs