prefer-string-starts-ends-with
Enforce using
String#startsWith
andString#endsWith
over other equivalent methods of checking substrings.
在 ESLint 配置 中扩展"plugin:@typescript-eslint/stylistic-type-checked"
可启用此规则。
此规则报告的一些问题可通过 --fix
ESLint 命令行选项自动修复。
该规则需要 类型信息 才能运行。
有多种方法可以验证字符串是否以特定字符串开头或结尾,例如 foo.indexOf('bar') === 0
。
截至 ES2015,JavaScript 中最常见的方式是使用 String#startsWith
和 String#endsWith
。
始终坚持这些方法有助于提高代码的可读性。
英:There are multiple ways to verify if a string starts or ends with a specific string, such as foo.indexOf('bar') === 0
.
As of ES2015, the most common way in JavaScript is to use String#startsWith
and String#endsWith
.
Keeping to those methods consistently helps with code readability.
此规则报告何时可以用 String#startsWith
或 String#endsWith
安全地替换字符串方法。
英:This rule reports when a string method can be replaced safely with String#startsWith
or String#endsWith
.
module.exports = {
"rules": {
"@typescript-eslint/prefer-string-starts-ends-with": "error"
}
};
示例
- ❌ 不正确
- ✅ 正确
declare const foo: string;
// starts with
foo[0] === 'b';
foo.charAt(0) === 'b';
foo.indexOf('bar') === 0;
foo.slice(0, 3) === 'bar';
foo.substring(0, 3) === 'bar';
foo.match(/^bar/) != null;
/^bar/.test(foo);
// ends with
foo[foo.length - 1] === 'b';
foo.charAt(foo.length - 1) === 'b';
foo.lastIndexOf('bar') === foo.length - 3;
foo.slice(-3) === 'bar';
foo.substring(foo.length - 3) === 'bar';
foo.match(/bar$/) != null;
/bar$/.test(foo);
Open in Playgrounddeclare const foo: string;
// starts with
foo.startsWith('bar');
// ends with
foo.endsWith('bar');
Open in Playground何时不使用它
如果你不介意使用哪种类型的字符串检查,则可以安全地关闭此规则。 但是,请记住,不一致的风格可能会损害项目的可读性。
英:If you don't mind which style of string checking is used, you can turn this rule off safely. However, keep in mind that inconsistent style can harm readability in a project.
选项
该规则不可配置。