在JavaScript中,判断一个字符串是否以特定的子字符串结尾,可以使用String.prototype.endsWith()
方法。这个方法是ES6中引入的,用于检查字符串是否以指定的后缀结束。
let str = "Hello, world!";
console.log(str.endsWith("world!")); // 输出: true
console.log(str.endsWith("World!")); // 输出: false,因为区分大小写
endsWith()
方法返回一个布尔值(true
或false
)。
.jpg
或.png
结尾。https://
)或路径结尾。// 验证文件扩展名
function isImageFile(filename) {
return filename.endsWith('.jpg') || filename.endsWith('.png') || filename.endsWith('.gif');
}
console.log(isImageFile("photo.jpg")); // 输出: true
console.log(isImageFile("document.pdf")); // 输出: false
// URL验证
function isSecureUrl(url) {
return url.endsWith('https://');
}
console.log(isSecureUrl("https://example.com")); // 输出: true
console.log(isSecureUrl("http://example.com")); // 输出: false
endsWith()
方法是大小写敏感的。如果不希望区分大小写,可以先将字符串转换为同一大小写,再进行比较。let str = "Hello, World!";
console.log(str.toLowerCase().endsWith("world!")); // 输出: true
endsWith()
方法在空字符串上调用会返回false
,除非检查的子字符串也是空的。let emptyStr = "";
console.log(emptyStr.endsWith("")); // 输出: true,因为空字符串以空字符串结尾
console.log(emptyStr.endsWith("a")); // 输出: false
endsWith()
方法是ES6引入的,如果需要在旧版浏览器中使用,可以考虑使用polyfill或者自定义实现。if (!String.prototype.endsWith) {
String.prototype.endsWith = function(searchString, position) {
var str = this.toString();
if (position === undefined || position > str.length) {
position = str.length;
}
position -= searchString.length;
var lastIndex = str.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
}
这个自定义实现考虑了endsWith()
方法的两个参数:要搜索的子字符串和开始搜索的位置。如果未提供位置参数,则默认从字符串的末尾开始搜索。
领取专属 10元无门槛券
手把手带您无忧上云