Skip to content

Latest commit

Β 

History

History
32 lines (21 loc) Β· 1.69 KB

File metadata and controls

32 lines (21 loc) Β· 1.69 KB

prefer-single-replace

πŸ“ 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.

Examples

// ❌
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, '_');