endsWith() 方法用于判断一个字符串是否以指定字符串结尾,如果是则返回 true,否则返回 false。
JavaScript Demo: String.endsWith()
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
语法
endsWith(searchString)
endsWith(searchString, endPosition)
参数
searchStringendPosition- : 预期找到
searchString的末尾位置(即searchString最后一个字符的索引加 1)。默认为str.length。
- : 预期找到
返回值
如果被检索字符串的末尾出现了指定的字符串(包括 searchString 为空字符串的情况),则返回 true;否则返回 false。
异常
- TypeError
- : 如果
searchString是一个正则表达式,则会抛出。
- : 如果
描述
这个方法可以让你确定一个字符串是否以另一个字符串结尾。该方法区分大小写。
示例
使用 endsWith()
const str = "生存还是毁灭,这是一个问题。";
console.log(str.endsWith("问题。")); // true
console.log(str.endsWith("毁灭")); // false
console.log(str.endsWith("毁灭", 6)); // true
规范
浏览器兼容性
参见
core-js中String.prototype.endsWith的 polyfill- String.prototype.startsWith()
- String.prototype.includes()
- String.prototype.indexOf()
- String.prototype.lastIndexOf()
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
