If the first parameter of String.replace
is a regular expression, a special syntax can be used in the replacement string to reference
capturing groups. Use $n
to reference the group by number and $<Name>
to reference the group by name. Because
replacements strings in String.replace
are interpreted at runtime, nothing prevents you to reference nonexisting group, with nonexisting
index or bad name, then the resulting string will be wrong. This rule statically validates that all referenced groups exist when replacing with
String.replace
or String.replaceAll
methods.
Noncompliant Code Example
const str = 'James Bond';
console.log(str.replace(/(\w+)\s(\w+)/, '$1, $0 $1')); // Noncompliant, index is 1-based, '$0' does not exist, prints 'James, $0 James'
console.log(str.replace(/(?<firstName>\w+)\s(?<lastName>\w+)/, '$<surname>, $<firstName> $<surname>')); // Noncompliant '$<surname>' does not exist, prints ', James '
Compliant Solution
const str = 'James Bond';
console.log(str.replace(/(\w+)\s(\w+)/, '$2, $1 $2'));
console.log(str.replace(/(?<firstName>\w+)\s(?<lastName>\w+)/, '$<lastName>, $<firstName> $<lastName>'));