String.prototype.endsWith()
endsWith() 方法用於確定一個字串的結尾是否是另一個指定的字串,返回 true 或 false。
試一試
const str1 = "Cats are the best!";
console.log(str1.endsWith("best!"));
// Expected output: true
console.log(str1.endsWith("best", 17));
// Expected output: true
const str2 = "Is this a question?";
console.log(str2.endsWith("question"));
// Expected output: false
語法
js
endsWith(searchString)
endsWith(searchString, endPosition)
引數
searchString-
要在
str結尾搜尋的字元。不能是 正則表示式。所有非正則表示式的值都會被 強制轉換為字串,因此省略此引數或傳遞undefined會導致endsWith()搜尋字串"undefined",這通常不是您想要的結果。 endPosition可選-
searchString預期出現的結束位置(searchString的最後一個字元的索引加 1)。預設為str.length。
返回值
如果給定的字元在字串結尾找到(包括 searchString 為空字串時),則返回 true;否則返回 false。
異常
描述
此方法可用於確定一個字串是否以另一個字串結尾。此方法區分大小寫。
示例
使用 endsWith()
js
const str = "To be, or not to be, that is the question.";
console.log(str.endsWith("question.")); // true
console.log(str.endsWith("to be")); // false
console.log(str.endsWith("to be", 19)); // true
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-string.prototype.endswith |
瀏覽器相容性
載入中…