Skip to content

Latest commit

 

History

History
54 lines (38 loc) · 1.31 KB

prefer-string-replace-all.md

File metadata and controls

54 lines (38 loc) · 1.31 KB

Prefer String#replaceAll() over regex searches with the global flag

🚫 This rule is disabled in the ✅ recommended config.

🔧 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.

Fail

string.replace(/RegExp with global flag/igu, '');
string.replace(/RegExp without special symbols/g, '');
string.replace(/\(It also checks for escaped regex symbols\)/g, '');
string.replace(/Works for u flag too/gu, '');
string.replaceAll(/foo/g, 'bar');

Pass

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