JS: Regex Syntax. Named Capture Group

By Xah Lee. Date: .

Named capture group

(?<name>…)

(new in ECMAScript 2018)

The group can be refered to by \k<name> in regex or $<name> in replacement string.

// match text where width and height are the same
console.log(
  /width="(?<w>\d+)" height="\k<w>"/.exec('width="300" height="300"'),
);
// [ 'width="300" height="300"', "300" ]
console.log(
  "lived from 1899 to 1960".replace(
    /.+(?<born>\d{4}).+(?<died>\d{4})/,
    "$<born> - $<died>",
  ),
);
// 1899 - 1960
\k<nanme>

Refer to named capture group name.