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

浏览器兼容性

另见