js实现enfwith
实现字符串以特定后缀结尾的检查
在JavaScript中检查字符串是否以特定后缀结尾可以通过几种方法实现。以下是常见的实现方式:

// 方法1:使用String.prototype.endsWith()
const str = 'Hello world';
const suffix = 'world';
const result = str.endsWith(suffix); // true
// 方法2:手动实现endsWith功能
function customEndsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
// 方法3:使用正则表达式
function regexEndsWith(str, suffix) {
return new RegExp(suffix + '$').test(str);
}
性能比较
- 原生
endsWith()方法性能最优,是ES6标准方法 - 手动实现版本在旧浏览器中可作为polyfill
- 正则表达式方法最灵活,可以处理复杂匹配模式
浏览器兼容性考虑
对于需要支持旧浏览器的项目,可以添加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;
};
}
实际应用示例
检查文件扩展名:
const filename = 'document.pdf';
const isPDF = filename.endsWith('.pdf'); // true
检查URL协议:
const url = 'https://example.com';
const isSecure = url.endsWith('s://'); // false
// 更合适的做法是检查开头
const isSecure = url.startsWith('https://'); // true






