Skip to content

regexNamedReplacements

Reports indexed references in replacement strings that should use named references.

✅ This rule is included in the ts stylisticStrict presets.

When using String.prototype.replace() or String.prototype.replaceAll() with a regular expression that has named capturing groups, the replacement string should use named references ($<name>) instead of indexed references ($1, $2, etc.).

Named references make the code more self-documenting and less prone to errors when the regex pattern is modified.

const result = "str".replace(/a(?<name>b)c/, "_$1_");
const result = "2024-01-15".replace(
/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/,
"$2/$3/$1",
);

This rule is not configurable.

If you prefer the brevity of indexed replacements, or if your codebase has established conventions around using indexed references even for named groups, you might prefer to disable this rule. Some developers find indexed references more familiar from other regex dialects.

Made with ❤️‍🔥 in Boston by Josh Goldberg and contributors.