Skip to content
← Back to rules

unicorn/prefer-string-starts-ends-with Correctness

This rule is turned on by default.
🛠️ An auto-fix is available for this rule.

它的作用

优先使用 String#startsWith()String#endsWith(),而不是使用 /^foo//foo$/ 的正则表达式。

为什么这不好?

使用 String#startsWith()String#endsWith() 更具可读性,而且性能更好,因为它不需要解析正则表达式。

示例

以下是此规则的错误代码示例:

javascript
const foo = "hello";
/^abc/.test(foo);

以下是此规则的正确代码示例:

javascript
const foo = "hello";
foo.startsWith("abc");

如何使用

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

json
{
  "rules": {
    "unicorn/prefer-string-starts-ends-with": "error"
  }
}
ts
import { defineConfig } from "oxlint";

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

版本

此规则添加于 v0.0.18。

参考资料