js实现endwith
实现 JavaScript 的 endsWith 方法
JavaScript 的 endsWith 方法用于检查字符串是否以指定的子字符串结尾。以下是几种实现方式:
使用原生 endsWith 方法
现代 JavaScript 已经原生支持 endsWith 方法:
const str = 'Hello, world!';
console.log(str.endsWith('world!')); // true
console.log(str.endsWith('Hello')); // false
手动实现 endsWith 功能
如果需要兼容旧版浏览器或自定义功能,可以手动实现:
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
const str = 'Hello, world!';
console.log(endsWith(str, 'world!')); // true
console.log(endsWith(str, 'Hello')); // false
使用 substring 实现
另一种方式是使用 substring 来检查字符串的结尾部分:
function endsWith(str, suffix) {
return str.substring(str.length - suffix.length) === suffix;
}
const str = 'Hello, world!';
console.log(endsWith(str, 'world!')); // true
console.log(endsWith(str, 'Hello')); // false
考虑大小写的实现
如果需要忽略大小写,可以转换为统一大小写后再比较:
function endsWith(str, suffix, ignoreCase = false) {
if (ignoreCase) {
str = str.toLowerCase();
suffix = suffix.toLowerCase();
}
return str.substring(str.length - suffix.length) === suffix;
}
const str = 'Hello, world!';
console.log(endsWith(str, 'WORLD!', true)); // true
console.log(endsWith(str, 'hello', true)); // false
性能优化版本
对于长字符串,可以使用 lastIndexOf 来优化性能:

function endsWith(str, suffix) {
const lastIndex = str.lastIndexOf(suffix);
return lastIndex !== -1 && lastIndex === str.length - suffix.length;
}
const str = 'Hello, world!';
console.log(endsWith(str, 'world!')); // true
console.log(endsWith(str, 'Hello')); // false
以上方法可以根据具体需求选择使用,原生 endsWith 方法是最简单高效的选择。






