Groups and Backreferences

Grouping and Back References (Duplicate Named Groups)

Parentheses group and capture; (?:…) groups without capturing; (?<name>…) captures into match.groups. In the pattern, \1 or \k<name> repeats what a group matched. In a replacement, $1, $<name>, $& (the match), ` $ ` (text before) and $'` (text after) insert pieces. ES2025 lets a name repeat in alternatives when only one of them can take part in a match; browsers have supported this (Baseline) since August 2024.

Named groups, back references and a duplicate group nameJavaScriptLive
const iso = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
console.log('2026-09-15'.replace(iso, '$<day>/$<month>/$<year>'));
console.log('abc'.replace(/b/, "[$`|$&|$']"));
console.log(/(?<q>['"]).*?\k<q>/.exec(`say "it's" now`)[0]);   // \k<q> repeats the quote
const month = /^(?:(?<y>\d{4})-(?<m>\d{2})|(?<m>\d{2})\/(?<y>\d{4}))$/;  // ES2025
for (const text of ['2026-09', '09/2026']) {
  const { y, m } = month.exec(text).groups;
  console.log(text, '->', y, m);
}