Skip to content
← Back to rules

unicorn/prefer-string-slice Pedantic

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

它的作用

优先使用 String#slice() 而不是 String#substr()String#substring()

为什么这不好?

String#substr()String#substring() 是两种较少人熟知的、用于截取字符串的旧式方式。最好使用 String#slice(),因为它更常用,行为更清晰,并且有一个一致的 Array 对应方法

示例

此规则的错误代码示例:

javascript
"foo".substr(1, 2);

此规则的正确代码示例:

javascript
"foo".slice(1, 2);

如何使用

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

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

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

版本

此规则在 v0.0.18 中添加。

参考资料