@typescript-eslint/prefer-string-starts-ends-with
Require startsWith and endsWith instead of other ways to test the start or end of a string
Also called typescript-eslint/prefer-string-starts-ends-with, typescript/prefer-string-starts-ends-with
There are many ways to ask whether a string starts or ends with some text: indexOf(...) === 0, slice(0, 3) === "...", charAt(0), s[0], a regular expression with ^ or $. Each one makes the reader work out the indexes. startsWith and endsWith say what you mean.
--fix rewrites the check to startsWith or endsWith where that can't change the result.
Configure#
Off by default. This rule needs types, so turning it on makes bun lint type check your code first.
[lint.rules]
"@typescript-eslint/prefer-string-starts-ends-with" = "error" # or "warn"Every option, set to its default:
[lint.rules]
"@typescript-eslint/prefer-string-starts-ends-with" = ["error", {
allowSingleElementEquality = "never", # "always" or "never"
}]Examples#
function isApiRoute(path: string) {
return path.indexOf("/api") === 0Use String#startsWith method instead.;
}
function isHidden(name: string) {
return name[0] === "."Use String#startsWith method instead.;
}
function isTypeScript(file: string) {
return file.slice(-3) === ".ts"Use the String#endsWith method instead. || /\.tsx$/.test(file)Use the String#endsWith method instead.;
}function isApiRoute(path: string) {
return path.startsWith("/api");
}
function isHidden(name: string) {
return name.startsWith(".");
}
function isTypeScript(file: string) {
return file.endsWith(".ts") || file.endsWith(".tsx");
}Indexes and methods such as indexOf are only reported on a string. On an array they're fine:
function startsWithHome(segments: string[]) {
return segments[0] === "~" || segments.indexOf("home") === 0;
}Options#
| Option | Default | What it does |
|---|---|---|
allowSingleElementEquality | "never" | With "always", allow comparing the first or last character, such as s[0] === "a" or s.charAt(0) === "a". |
{ "allowSingleElementEquality": "always" }No problemsfunction isHidden(name: string) {
return name[0] === "." || name.charAt(name.length - 1) === "~";
}