什么是 endWith?
endsWith() 是 JavaScript 字符串对象的一个内置方法,用于检测当前字符串是否以指定的子字符串结尾,并返回一个布尔值(true 或 false)。
基本语法
str.endsWith(searchString[, length])
searchString:要搜索的子字符串。length(可选):作为字符串长度进行比较的最大长度。
示例代码
const filename = "document.pdf";
console.log(filename.endsWith(".pdf")); // true
console.log(filename.endsWith(".doc")); // false
// 使用 length 参数
console.log("hello world".endsWith("world", 5)); // false(只检查前5个字符)
console.log("hello world".endsWith("hello", 5)); // true
浏览器兼容性
endsWith() 方法在 ECMAScript 2015 (ES6) 中引入。现代浏览器普遍支持,但在 IE 中不支持。如需兼容旧环境,可使用以下 Polyfill:
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(search, this_len) {
if (this_len === undefined || this_len > this.length) {
this_len = this.length;
}
return this.substring(this_len - search.length, this_len) === search;
};
}
常见用途
- 验证文件扩展名(如 .jpg、.json)
- 检查 URL 是否以特定路径结尾
- 文本处理中的格式校验