Skip to content

regexUnnecessaryDollarReplacements

Reports replacement string references to capturing groups that do not exist in the pattern.

✅ This rule is included in the ts logical and logicalStrict 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.

const result = "ab".replace(/(a)(b)/, "$3");
const result = "ab".replace(/a/, "$1");
const result = "ab".replace(/(?<first>a)/, "$<middle>");

This rule is not configurable.

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.

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