Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5592a2c

Browse files
mysticateabradzacher
authored andcommitted
feat(eslint-plugin): add prefer-string-starts-ends-with rule (typescript-eslint#289)
Fixes typescript-eslint#285
1 parent 5311342 commit 5592a2c

File tree

5 files changed

+1748
-2
lines changed

5 files changed

+1748
-2
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Enforce the use of `String#startsWith` and `String#endsWith` instead of other equivalent methods of checking substrings (prefer-string-starts-ends-with)
2+
3+
There are multiple ways to verify if a string starts or ends with a specific string, such as `foo.indexOf('bar') === 0`.
4+
5+
Since ES2015 has added `String#startsWith` and `String#endsWith`, this rule reports other ways to be consistent.
6+
7+
## Rule Details
8+
9+
This rule is aimed at enforcing a consistent way to check whether a string starts or ends with a specific string.
10+
11+
Examples of **incorrect** code for this rule:
12+
13+
```ts
14+
let foo: string;
15+
16+
// starts with
17+
foo[0] === 'b';
18+
foo.charAt(0) === 'b';
19+
foo.indexOf('bar') === 0;
20+
foo.slice(0, 3) === 'bar';
21+
foo.substring(0, 3) === 'bar';
22+
foo.match(/^bar/) != null;
23+
/^bar/.test(foo);
24+
25+
// ends with
26+
foo[foo.length - 1] === 'b';
27+
foo.charAt(foo.length - 1) === 'b';
28+
foo.lastIndexOf('bar') === foo.length - 3;
29+
foo.slice(-3) === 'bar';
30+
foo.substring(foo.length - 3) === 'bar';
31+
foo.match(/bar$/) != null;
32+
/bar$/.test(foo);
33+
```
34+
35+
Examples of **correct** code for this rule:
36+
37+
```ts
38+
foo.startsWith('bar');
39+
foo.endsWith('bar');
40+
```
41+
42+
## Options
43+
44+
There are no options.
45+
46+
```JSON
47+
{
48+
"@typescript-eslint/prefer-string-starts-ends-with": "error"
49+
}
50+
```
51+
52+
## When Not To Use It
53+
54+
If you don't mind that style, you can turn this rule off safely.

0 commit comments

Comments
 (0)