Перейти до вмісту

useStringStartsEndsWith

Цей контент ще не доступний вашою мовою.

biome.json
{
"linter": {
"rules": {
"nursery": {
"useStringStartsEndsWith": "error"
}
}
}
}

Prefer String#startsWith() and String#endsWith() over verbose prefix and suffix checks.

This rule detects common string comparisons such as indexing, charAt, indexOf, lastIndexOf, slice, substring, match, and anchored RegExp#test calls when they are being used to check whether a string starts or ends with another string.

The rule uses type information and only reports when the receiver is known to be a string. Array indexing and other non-string receivers are ignored.

invalid-index.ts
declare const text: string;
text[0] === "a";
/invalid-index.ts:2:1 lint/nursery/useStringStartsEndsWith  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This index access comparison looks like you’re checking a string prefix.

1 │ declare const text: string;
> 2 │ text[0] === “a”;
^^^^^^^^^^^^^^^
3 │

Using the built-in string method is clearer and easier to read.

This rule belongs to the nursery group, which means it is not yet stable and may change in the future. Visit https://biomejs.dev/linter/#nursery for more information.

Unsafe fix: Use startsWith() instead.

1 1 declare const text: string;
2 - text[0]·===·a;
2+ text.startsWith(a);
3 3

invalid-search.ts
declare const text: string;
text.indexOf("foo") === 0;
/invalid-search.ts:2:1 lint/nursery/useStringStartsEndsWith  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This indexOf() comparison looks like you’re checking a string prefix.

1 │ declare const text: string;
> 2 │ text.indexOf(“foo”) === 0;
^^^^^^^^^^^^^^^^^^^^^^^^^
3 │

Using the built-in string method is clearer and easier to read.

This rule belongs to the nursery group, which means it is not yet stable and may change in the future. Visit https://biomejs.dev/linter/#nursery for more information.

Unsafe fix: Use startsWith() instead.

1 1 declare const text: string;
2 - text.indexOf(foo)·===·0;
2+ text.startsWith(foo);
3 3

invalid-regex.ts
declare const text: string;
/^foo/.test(text);
/invalid-regex.ts:2:1 lint/nursery/useStringStartsEndsWith  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This anchored RegExp#test() call looks like you’re checking a string prefix.

1 │ declare const text: string;
> 2 │ /^foo/.test(text);
^^^^^^^^^^^^^^^^^
3 │

Using the built-in string method is clearer and easier to read.

This rule belongs to the nursery group, which means it is not yet stable and may change in the future. Visit https://biomejs.dev/linter/#nursery for more information.

Unsafe fix: Use startsWith() instead.

1 1 declare const text: string;
2 - /^foo/.test(text);
2+ text.startsWith(foo);
3 3

valid-string.ts
declare const text: string;
text.startsWith("foo");
text.endsWith("bar");
valid-array.ts
declare const list: string[];
list[0] === "a";