π Enforce combining multiple single-character replacements into a single String#replaceAll() with a regular expression.
πΌ This rule is enabled in the following configs: β
recommended, βοΈ unopinionated.
π§ This rule is automatically fixable by the --fix CLI option.
A chain of replacements that each swap a single character for the same string scans the whole string once per call. When the replacements are global and share the same result, they can be combined into a single pass using a regular expression character class, which is both faster and clearer.
Only global replacements are handled: String#replaceAll() with a single-character string, and String#replace()/String#replaceAll() with a regex matching one literal character and the global flag. Plain String#replace('a', β¦) is left alone because it only replaces the first occurrence, so it has no character-class equivalent.
// β
const slug = string.replaceAll('a', '-').replaceAll('b', '-').replaceAll('c', '-');
// β
const slug = string.replaceAll(/[abc]/g, '-');// β
const cleaned = string.replace(/a/g, '_').replaceAll('b', '_');
// β
const cleaned = string.replaceAll(/[ab]/g, '_');