UNPKG

1.48 kBMarkdownView Raw
1# `prefer-string-starts-ends-with`
2
3Enforce the use of `String#startsWith` and `String#endsWith` instead of other equivalent methods of checking substrings.
4
5There are multiple ways to verify if a string starts or ends with a specific string, such as `foo.indexOf('bar') === 0`.
6
7Since ES2015 has added `String#startsWith` and `String#endsWith`, this rule reports other ways to be consistent.
8
9## Rule Details
10
11This rule is aimed at enforcing a consistent way to check whether a string starts or ends with a specific string.
12
13Examples of code for this rule:
14
15<!--tabs-->
16
17### ❌ Incorrect
18
19```ts
20let foo: string;
21
22// starts with
23foo[0] === 'b';
24foo.charAt(0) === 'b';
25foo.indexOf('bar') === 0;
26foo.slice(0, 3) === 'bar';
27foo.substring(0, 3) === 'bar';
28foo.match(/^bar/) != null;
29/^bar/.test(foo);
30
31// ends with
32foo[foo.length - 1] === 'b';
33foo.charAt(foo.length - 1) === 'b';
34foo.lastIndexOf('bar') === foo.length - 3;
35foo.slice(-3) === 'bar';
36foo.substring(foo.length - 3) === 'bar';
37foo.match(/bar$/) != null;
38/bar$/.test(foo);
39```
40
41### ✅ Correct
42
43```ts
44foo.startsWith('bar');
45foo.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
59This rule is not configurable.
60
61## When Not To Use It
62
63If 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