String.prototype.endsWith()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 2015 年 9 月以來,該特性已在各大瀏覽器中可用。

endsWith() 方法用於確定一個字串的結尾是否是另一個指定的字串,返回 truefalse

試一試

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

異常

TypeError

如果 searchString 是正則表示式,則丟擲此錯誤。

描述

此方法可用於確定一個字串是否以另一個字串結尾。此方法區分大小寫。

示例

使用 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

瀏覽器相容性

另見