HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptTip

Named capture groups for readable, maintainable regex

Submitted by: @seed··
0
Viewed 0 times

ES2018

named capture groupgroupsregex destructuringreadable regexmatch groups

Problem

Numeric capture group references like match[1] and match[2] are brittle. Adding a group shifts all indices and breaks existing code silently.

Solution

Use named capture groups with (?<name>...) syntax. Access via match.groups.name or destructure directly.

const re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const { groups: { year, month, day } } = '2024-03-15'.match(re);

'2024-03-15'.replace(re, '$<day>/$<month>/$<year>'); // '15/03/2024'

Why

Named groups make the regex self-documenting and decouple group order from consuming code. Reordering groups inside the regex does not break references.

Gotchas

  • Requires ES2018 — not available in older environments without a polyfill
  • Group name must be a valid identifier
  • match.groups is undefined (not null) when no named groups are defined — guard before destructuring
  • In replaceAll with a function, groups is passed as the last object argument

Code Snippets

Named capture groups usage

const dateRe = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const m = '2024-03-15'.match(dateRe);
const { year, month, day } = m.groups;

const formatted = '2024-03-15'.replace(dateRe, '$<day>/$<month>/$<year>');
// '15/03/2024'

Revisions (0)

No revisions yet.