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
const result: string
result
= "ab".
String.replace(searchValue: {
[Symbol.replace](string: string, replaceValue: string): string;
}, replaceValue: string): string (+3 overloads)

Passes a string and {@linkcode replaceValue } to the [Symbol.replace] method on {@linkcode searchValue } . This method is expected to implement its own replacement algorithm.

@paramsearchValue An object that supports searching for and replacing matches within a string.

@paramreplaceValue The replacement text.

replace
(/(a)(b)/, "$3");
const
const result: string
result
= "ab".
String.replace(searchValue: {
[Symbol.replace](string: string, replaceValue: string): string;
}, replaceValue: string): string (+3 overloads)

Passes a string and {@linkcode replaceValue } to the [Symbol.replace] method on {@linkcode searchValue } . This method is expected to implement its own replacement algorithm.

@paramsearchValue An object that supports searching for and replacing matches within a string.

@paramreplaceValue The replacement text.

replace
(/a/, "$1");
const
const result: string
result
= "ab".
String.replace(searchValue: {
[Symbol.replace](string: string, replaceValue: string): string;
}, replaceValue: string): string (+3 overloads)

Passes a string and {@linkcode replaceValue } to the [Symbol.replace] method on {@linkcode searchValue } . This method is expected to implement its own replacement algorithm.

@paramsearchValue An object that supports searching for and replacing matches within a string.

@paramreplaceValue The replacement text.

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 ❤️‍🔥 around the world by the Flint team and contributors.