跳至主要內容

優先使用字串 starts-ends-with

強制使用 String#startsWithString#endsWith 來檢查子字串,而不是其他等價方法。

🎨

擴充 "plugin:@typescript-eslint/stylistic-type-checked" ESLint 設定 中可以啟用此規則。

🔧

此規則所報告的某些問題可以透過 ESLint 命令列選項 --fix 自動修復.

💭

此規則需要 類型資訊 才能執行。

驗證字串是否以特定字串開頭或結尾有很多種方法,例如 foo.indexOf('bar') === 0。自 ES2015 以來,JavaScript 中最常見的方式是使用 String#startsWithString#endsWith。始終使用這些方法有助於提高程式碼可讀性。

此規則會報告當可以安全使用 String#startsWithString#endsWith 取代字串方法時。

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/prefer-string-starts-ends-with": "error"
}
};

在遊戲場中試用此規則 ↗

範例

declare const 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/) != null;
/^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$/) != null;
/bar$/.test(foo);
在遊樂場中開啟

選項

此規則接受下列選項

type Options = [
{
/** Whether to allow equality checks against the first or last element of a string. */
allowSingleElementEquality?:
| 'never'
/** Whether to allow equality checks against the first or last element of a string. */
| 'always';
},
];

const defaultOptions: Options = [{ allowSingleElementEquality: 'never' }];

allowSingleElementEquality

如果切換到 'always',此規則將允許字串中第一個或最後一個字元的相等檢查。在不處理特殊字元編碼並偏好更簡潔風格的專案中,這可能會比較好。

預設情況下,以下程式碼被視為不正確,但允許使用 allowSingleElementEquality: 'always'

declare const text: string;

text[0] === 'a';
text[0] === text[0].toUpperCase();
text[0] === text[1];
text[text.length - 1] === 'b';
在遊樂場中開啟

不建議使用的時機

如果你不介意使用哪一種字串檢查風格,你可以安全地關閉此規則。但是,請記住不一致的風格可能會損害專案的可讀性。


經過類型檢查的 linter 規則比傳統的 linter 規則更強大,但還需要設定 類型檢查的 linting。如果在啟用類型檢查規則後遇到效能下降的問題,請參閱 效能疑難排解

資源