Skip to content
NewBun 1.4.5 is out. Release notes
AphrodyBun

Linter · Rules

@typescript-eslint/prefer-string-starts-ends-with

Require startsWith and endsWith instead of other ways to test the start or end of a string

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.

bunfig.toml
[lint.rules]
"@typescript-eslint/prefer-string-starts-ends-with" = "error" # or "warn"

Every option, set to its default:

bunfig.toml
[lint.rules]
"@typescript-eslint/prefer-string-starts-ends-with" = ["error", {
  allowSingleElementEquality = "never", # "always" or "never"
}]

Examples

Reported:

function isApiRoute(path: string) {
  return path.indexOf("/api") === 0;
}

function isHidden(name: string) {
  return name[0] === ".";
}

function isTypeScript(file: string) {
  return file.slice(-3) === ".ts" || /\.tsx$/.test(file);
}

Not reported:

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

OptionDefaultWhat it does
allowSingleElementEquality"never"With "always", allow comparing the first or last character, such as s[0] === "a" or s.charAt(0) === "a".
function isHidden(name: string) {
  return name[0] === "." || name.charAt(name.length - 1) === "~";
}