regexUnnecessaryDollarReplacements
Reports replacement string references to capturing groups that do not exist in the pattern.
✅ This rule is included in the ts logical presets.
When using String.prototype.replace() or String.prototype.replaceAll() with a replacement string, referencing capturing groups that do not exist in the pattern is likely a mistake.
This includes numeric references like $3 when only two groups exist, or named references like $<middle> when no such named group exists.
These invalid references will be treated as literal text in the output, which is rarely the intended behavior.
This rule reports dollar replacements that are either invalid or unnecessary.
Examples
Section titled “Examples”const result = "ab".replace(/(a)(b)/, "$3");const result = "ab".replace(/a/, "$1");const result = "ab".replace(/(?<first>a)/, "$<middle>");const result = "ab".replace(/(a)(b)/, "$2$1");const result = "ab".replace(/(?<first>a)/, "$<first>");const result = "ab".replace(/a/, "$&");const result = "ab".replace(/a/, "$$1");Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you intentionally use invalid dollar replacements as literal text (though this is rare and confusing), you might want to disable this rule.
Consider escaping the dollar sign with $$ instead for clarity.