Skip to content

Latest commit

 

History

History
37 lines (26 loc) · 728 Bytes

prefer-string-replace-all.md

File metadata and controls

37 lines (26 loc) · 728 Bytes

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

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.

This rule is fixable.

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