unicorn/prefer-string-replace-all 严格
它的作用
当使用带有全局标志的正则表达式时,推荐使用 String#replaceAll() 而非 String#replace()。
为什么这是不好的?
String#replaceAll() 方法在性能上更快且更安全,因为无需使用正则表达式,并且不必记住在字符串不是字面量时对其进行转义。此外,当与正则表达式一起使用时,其意图更加清晰。
示例
此规则的错误代码示例:
js
foo.replace(/a/g, bar);此规则的正确代码示例:
js
foo.replace(/a/, bar);
foo.replaceAll(/a/, bar);
const pattern = "not-a-regexp";
foo.replace(pattern, bar);如何使用
要通过配置文件或 CLI 启用此规则,可以使用:
json
{
"rules": {
"unicorn/prefer-string-replace-all": "error"
}
}bash
oxlint --deny unicorn/prefer-string-replace-all