Skip to main content

prefer-string-starts-ends-with

强制使用 String#startsWithString#endsWith 而不是其他等效的检查子字符串的方法.

🔧

此规则报告的一些问题可通过 --fix ESLint 命令行选项自动修复

💭

该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。

有多种方法可以验证字符串是否以特定字符串开头或结尾,例如 foo.indexOf('bar') === 0。截至 ES2015,JavaScript 中最常用的方法是使用 String#startsWithString#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.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/prefer-string-starts-ends-with": "error"
}
});

在线运行试试这个规则 ↗

示例

¥Examples

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 Playground

选项

该规则接受以下选项:

type Options = [
{
/** 是否允许针对字符串的第一个或最后一个元素进行相等性检查。 */
allowSingleElementEquality?:
| 'never'
/** 是否允许针对字符串的第一个或最后一个元素进行相等性检查。 */
| 'always';
},
];

const defaultOptions: Options = [{ allowSingleElementEquality: 'never' }];

¥Options

allowSingleElementEquality

是否允许针对字符串的第一个或最后一个元素进行相等性检查。 Default: "never".

如果切换到 'always',规则将允许对字符串中的第一个或最后一个字符进行相等性检查。这在不处理特殊字符编码且更喜欢更简洁风格的项目中可能是更好的选择。

¥If switched to 'always', the rule will allow equality checks against the first or last character in a string. This can be preferable in projects that don't deal with special character encodings and prefer a more succinct style.

以下代码默认被视为不正确,但 allowSingleElementEquality: 'always' 允许:

¥The following code is considered incorrect by default, but is allowed with allowSingleElementEquality: 'always':

declare const text: string;

text[0] === 'a';
text[0] === text[0].toUpperCase();
text[0] === text[1];
text[text.length - 1] === 'b';
Open in Playground

何时不使用它

¥When Not To Use It

如果你不介意使用哪种类型的字符串检查,则可以安全地关闭此规则。但是,请记住,不一致的风格可能会损害项目的可读性。

¥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.


Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.

See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.

资源