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 |
浏览器兼容性
加载中…