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