Skip to content

Latest commit

 

History

History
21 lines (15 loc) · 627 Bytes

prefer-replace-all.md

File metadata and controls

21 lines (15 loc) · 627 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, '');

Pass

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