Skip to content

Commit

Permalink
feat(eslint-plugin): add prefer-string-starts-ends-with rule (fixes #285
Browse files Browse the repository at this point in the history
)
  • Loading branch information
mysticatea committed Feb 16, 2019
1 parent 1464696 commit 0a10459
Show file tree
Hide file tree
Showing 7 changed files with 1,825 additions and 3 deletions.
@@ -0,0 +1,54 @@
# Enforce to use `String#startsWith` and `String#endsWith` over other options (prefer-string-starts-ends-with)

There are multiple ways to verify if a string starts or ends with a specific string, auch as `foo.indexOf('bar') === 0`.

Since ES2015 has added `String#startsWith` and `String#endsWith`, this rule reports other ways to be consistent.

## Rule Details

This rule is aimed at enforcing the consistent way that checks a string starts or ends with a specific string.

Examples of **incorrect** code for this rule:

```ts
let 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/)
/^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$/)
/bar$/.test(foo)
```

Examples of **correct** code for this rule:

```ts
foo.startsWith('bar');
foo.endsWith('bar');
```

## Options

There is no option.

```JSON
{
"@typescript-eslint/prefer-string-starts-ends-with": "error"
}
```

## When Not To Use It

If you don't mind that style, you can turn this rule off safely.
2 changes: 2 additions & 0 deletions packages/eslint-plugin/package.json
Expand Up @@ -37,6 +37,8 @@
"dependencies": {
"@typescript-eslint/parser": "1.3.0",
"@typescript-eslint/typescript-estree": "1.3.0",
"eslint-utils": "^1.3.1",
"regexpp": "^2.0.1",
"requireindex": "^1.2.0",
"tsutils": "^3.7.0"
},
Expand Down

0 comments on commit 0a10459

Please sign in to comment.