js实现enfwith
实现字符串 endsWith 功能的 JavaScript 方法
使用原生 String.prototype.endsWith
JavaScript 原生提供了 endsWith 方法,可直接判断字符串是否以特定子串结尾:
const str = 'Hello, world!';
const result = str.endsWith('world!');
console.log(result); // 输出 true
手动实现 endsWith 功能
若需兼容不支持 endsWith 的环境,可通过以下方式实现:

function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
const str = 'Hello, world!';
console.log(endsWith(str, 'world!')); // 输出 true
处理大小写敏感问题
默认情况下 endsWith 是大小写敏感的,若需忽略大小写:

function endsWithCaseInsensitive(str, suffix) {
return str.toLowerCase().endsWith(suffix.toLowerCase());
}
const str = 'Hello, WORLD!';
console.log(endsWithCaseInsensitive(str, 'world!')); // 输出 true
扩展实现支持多后缀检测
需要检测多个可能的结尾时:
function endsWithAny(str, suffixes) {
return suffixes.some(suffix => str.endsWith(suffix));
}
const str = 'example.txt';
console.log(endsWithAny(str, ['.jpg', '.txt'])); // 输出 true
性能优化版本
对于超长字符串的性能优化实现:
function optimizedEndsWith(str, suffix) {
const strLen = str.length;
const suffixLen = suffix.length;
if (suffixLen > strLen) return false;
return str.slice(strLen - suffixLen) === suffix;
}






