Skip to content

Latest commit

Β 

History

History
69 lines (50 loc) Β· 1.63 KB

File metadata and controls

69 lines (50 loc) Β· 1.63 KB

prefer-string-replace-all

πŸ“ Prefer String#replaceAll() over regex searches with the global flag.

πŸ’Ό This rule is enabled in the following configs: βœ… recommended, β˜‘οΈ unopinionated.

πŸ”§ This rule is automatically fixable by the --fix CLI option.

The String#replaceAll() method is both faster and safer as you don't have to use a regex and remember to escape it if the string is not a literal. And when used with a regex, it makes the intent clearer.

Examples

// ❌
string.replace(/RegExp with global flag/igu, '');

// βœ…
string.replaceAll(/RegExp with global flag/igu, '');
// ❌
string.replace(/RegExp without special symbols/g, '');

// βœ…
string.replaceAll('RegExp without special symbols', '');
// ❌
string.replace(/\(It also checks for escaped regex symbols\)/g, '');

// βœ…
string.replaceAll('(It also checks for escaped regex symbols)', '');
// ❌
string.replace(/Works for u flag too/gu, '');

// βœ…
string.replaceAll('Works for u flag too', '');
// ❌
string.replaceAll(/foo/g, 'bar');

// βœ…
string.replaceAll('foo', 'bar');
// βœ…
string.replace(/Non-global regexp/iu, '');
// βœ…
string.replace('Not a regex expression', '')
// βœ…
string.replaceAll(/\s/g, '');