1 | # `prefer-string-starts-ends-with`
|
2 |
|
3 | Enforce the use of `String#startsWith` and `String#endsWith` instead of other equivalent methods of checking substrings.
|
4 |
|
5 | There are multiple ways to verify if a string starts or ends with a specific string, such as `foo.indexOf('bar') === 0`.
|
6 |
|
7 | Since ES2015 has added `String#startsWith` and `String#endsWith`, this rule reports other ways to be consistent.
|
8 |
|
9 | ## Rule Details
|
10 |
|
11 | This rule is aimed at enforcing a consistent way to check whether a string starts or ends with a specific string.
|
12 |
|
13 | Examples of code for this rule:
|
14 |
|
15 |
|
16 |
|
17 | ### ❌ Incorrect
|
18 |
|
19 | ```ts
|
20 | let foo: string;
|
21 |
|
22 | // starts with
|
23 | foo[0] === 'b';
|
24 | foo.charAt(0) === 'b';
|
25 | foo.indexOf('bar') === 0;
|
26 | foo.slice(0, 3) === 'bar';
|
27 | foo.substring(0, 3) === 'bar';
|
28 | foo.match(/^bar/) != null;
|
29 | /^bar/.test(foo);
|
30 |
|
31 | // ends with
|
32 | foo[foo.length - 1] === 'b';
|
33 | foo.charAt(foo.length - 1) === 'b';
|
34 | foo.lastIndexOf('bar') === foo.length - 3;
|
35 | foo.slice(-3) === 'bar';
|
36 | foo.substring(foo.length - 3) === 'bar';
|
37 | foo.match(/bar$/) != null;
|
38 | /bar$/.test(foo);
|
39 | ```
|
40 |
|
41 | ### ✅ Correct
|
42 |
|
43 | ```ts
|
44 | foo.startsWith('bar');
|
45 | foo.endsWith('bar');
|
46 | ```
|
47 |
|
48 | ## Options
|
49 |
|
50 | ```jsonc
|
51 | // .eslintrc.json
|
52 | {
|
53 | "rules": {
|
54 | "@typescript-eslint/prefer-string-starts-ends-with": "warn"
|
55 | }
|
56 | }
|
57 | ```
|
58 |
|
59 | This rule is not configurable.
|
60 |
|
61 | ## When Not To Use It
|
62 |
|
63 | If you don't mind that style, you can turn this rule off safely.
|
64 |
|
65 | ## Attributes
|
66 |
|
67 | - Configs:
|
68 | - [ ] ✅ Recommended
|
69 | - [x] 🔒 Strict
|
70 | - [x] 🔧 Fixable
|
71 | - [x] 💭 Requires type information
|