endsWith() 方法用于判断一个字符串是否以指定的子字符串结束。如果满足条件,则返回 true;否则返回 false。
语法
str.endsWith(searchValue[, length])
searchValue: 必需。需要在原字符串末尾搜索的子字符串。length:可选。表示原字符串长度的一个整数。这个参数允许你指定一个可能比原字符串短的字符串,然后检查这个较短的字符串是否以searchValue结尾。默认值为原字符串的长度。
示例
基础示例
const str = "Hello World";
console.log(str.endsWith("World")); // 输出: true
console.log(str.endsWith("world")); // 输出: false (区分大小写)使用 length 参数
const str = "Hello World";
console.log(str.endsWith("Hello", 5)); // 输出: true (因为 "Hello" 长度为5)
console.log(str.endsWith("World", 5)); // 输出: false (因为 "World" 超出了5个字符)在循环中使用
// www.javascriptcn.com code example
const filenames = ["document.pdf", "image.png", "archive.zip", "notes.txt"];
const extensions = [".pdf", ".png", ".zip", ".txt"];
filenames.forEach(filename => {
extensions.some(extension => {
if (filename.endsWith(extension)) {
console.log(`文件 ${filename} 是一个 ${extension} 文件`);
return true; // 如果找到了匹配项,就停止搜索
}
return false;
});
});
// 输出:
// 文件 document.pdf 是一个 .pdf 文件
// 文件 image.png 是一个 .png 文件
// 文件 archive.zip 是一个 .zip 文件
// 文件 notes.txt 是一个 .txt 文件检查 URL 是否以特定协议结束
const url = "https://example.com/path/to/resource";
console.log(url.endsWith("https://")); // 输出: false
console.log(url.endsWith("//")); // 输出: false
console.log(url.endsWith("/")); // 输出: true处理空字符串
const emptyStr = "";
console.log(emptyStr.endsWith("")); // 输出: true (空字符串以任何字符串结尾都是 true)
console.log(emptyStr.endsWith("a")); // 输出: false与 startsWith() 和 includes() 方法对比
虽然 endsWith() 方法用于检查字符串是否以某个子串结束,但还有其他方法可以达到类似的效果:
startsWith(searchString, position):用于检查字符串是否以指定的子字符串开始。includes(searchValue, start):用于检查一个字符串是否包含指定的子字符串,不考虑位置。
const str = "Hello World";
console.log(str.endsWith("World")); // 输出: true
console.log(str.startsWith("Hello")); // 输出: true
console.log(str.includes("World")); // 输出: true这些方法提供了不同的方式来处理字符串中的模式匹配和位置检查。选择哪种方法取决于你的具体需求。
兼容性
endsWith() 方法是 ES6 引入的新特性,因此它在旧版浏览器中可能不可用。如果你需要兼容旧版本浏览器,可以考虑使用 polyfill 或者自己实现一个简单的版本。
// www.javascriptcn.com code example
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(searchString, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
position = subjectString.length;
}
position -= searchString.length;
var lastIndex = subjectString.lastIndexOf(searchString);
return position >= 0 && lastIndex === position;
};
}通过以上代码,即使在不支持 endsWith() 的环境中,也能正常工作。