Skip to content

Latest commit

 

History

History
42 lines (29 loc) · 1.07 KB

prefer-string-replace-all.md

File metadata and controls

42 lines (29 loc) · 1.07 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 escape the regex if the string is not a literal.

Fail

string.replace(/This has no special regex symbols/g, '');
string.replace(/\(It also checks for escaped regex symbols\)/g, '');
string.replace(/Works for u flag too/gu, '');

Pass

string.replace(/Non-literal characters .*/g, '');
string.replace(/Extra flags/gi, '');
string.replace('Not a regex expression', '')
string.replaceAll('Literal characters only', '');