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.
Examples
Section titled “Examples”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",);const result = "str".replace(/a(?<name>b)c/, "_$<name>_");const result = "2024-01-15".replace( /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/, "$<month>/$<day>/$<year>",);// Unnamed groups can use indexed referencesconst result = "str".replace(/a(b)c/, "_$1_");Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”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.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- ESLint:
regexp/prefer-named-replacement
Made with ❤️🔥 in Boston by
Josh Goldberg and contributors.