Skip to content
← Back to rules

unicorn/prefer-string-replace-all Pedantic

🛠️ An auto-fix is available for this rule.

作用

在使用带有全局标志的正则表达式时,优先使用 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);

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "rules": {
    "unicorn/prefer-string-replace-all": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "unicorn/prefer-string-replace-all": "error",
  },
});
bash
oxlint --deny unicorn/prefer-string-replace-all

版本

此规则是在 v0.0.18 中添加的。

参考资料