π 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.
// β
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, '');