This rule flags when String#replace() is used with a global regex pattern that is equivalent to a fixed literal string, or when
String#replaceAll() is used with a regex without the global flag.
The String#replaceAll() method was introduced in ES2021 to provide a clearer and safer way to replace all occurrences of a pattern in
a string.
When using String#replace() with a global regex for a fixed text match, developers must remember to include the global flag
(g) and properly escape special regex characters if the search pattern contains them. This can lead to bugs when special characters are
not escaped correctly.
For example, if you want to replace all dots in a string, using string.replace(/./g, '') will actually replace all characters (since
. matches any character in regex), not just literal dots. You would need string.replace(/\./g, '') instead.
With String#replaceAll(), you can simply use string.replaceAll('.', '') which is both safer and more readable. The method
name clearly indicates that all occurrences will be replaced.
However, some global regexes are not equivalent to a fixed string match. Character classes, capturing groups, quantified patterns, or flags such as
i can change which substrings are matched or how replacement values are produced. In those cases, String#replaceAll() with a
string literal would not preserve the original behavior.
When String#replaceAll() is used with a regex, the global flag is required, or a TypeError will be thrown.
Using the wrong replacement method can lead to unexpected behavior:
Replace String#replace() with String#replaceAll() using a string literal when the global regex only matches fixed literal
text and does not rely on regex-specific behavior.
const result = text.replace(/hello/g, 'hi'); // Noncompliant
const result = text.replaceAll('hello', 'hi');
No issue will be raised when the regex is needed to preserve the behavior of the replacement, such as when the pattern uses character classes, quantifiers, capturing groups, or flags that change matching.
const normalized = input.replace(/[{}\s]/g, '');
const collapsed = input.replace(/\s+/g, ' ');
const rewritten = input.replace(/(\w+):(\w+)/g, '$2:$1');
const normalizedCase = input.replace(/foo/ig, 'bar');