# @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.

{/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */}

## Configure

Off by default. This rule needs types, so turning it on makes `bun lint` type check your code first.

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

Every option, set to its default:

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

{/* End of the generated section. */}

## Examples

Reported:

{/* bad {"count": 4} */}
```ts
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:

{/* good */}
```ts
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:

{/* good */}
```ts
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"`. |

{/* good {"options": [{"allowSingleElementEquality": "always"}]} */}
```ts
function isHidden(name: string) {
  return name[0] === "." || name.charAt(name.length - 1) === "~";
}
```
