prefer-named-capture-group

Require capture groups in regular expressions to have a name

has suggestions

You read a numbered group as match[1], which says nothing about what it holds, and the number shifts when you add a group in front of it. You read a named group as match.groups.year, and that stays correct when the pattern changes.

A group that's only there for grouping can be non-capturing: (?:...).

A constant string passed to RegExp() or new RegExp() is checked too. The report comes with two suggestions: name the group, or make it non-capturing.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"prefer-named-capture-group" = "error" # or "warn"

Examples#

example.js3 problems
const date = /(\d{4})-(\d{2})/.exec(input);
const year = date[1];

const version = new RegExp("v([0-9]+)");
example.jsNo problems
const date = /(?<year>\d{4})-(?<month>\d{2})/.exec(input);
const year = date.groups.year;

const isImage = /\.(?:png|jpe?g)$/.test(file);