js endswith 实现
实现 JavaScript 的 endsWith 方法
在 JavaScript 中,endsWith 是字符串的内置方法,用于判断字符串是否以指定的子字符串结尾。以下是几种实现方式:

使用原生 endsWith 方法
现代浏览器和 Node.js 环境支持原生的 endsWith 方法:

const str = 'Hello, world!';
const result = str.endsWith('world!');
console.log(result); // true
手动实现 endsWith 函数
如果需要兼容旧环境或自定义逻辑,可以手动实现:
function endsWith(str, searchStr, position) {
if (position === undefined || position > str.length) {
position = str.length;
}
return str.substring(position - searchStr.length, position) === searchStr;
}
const str = 'Hello, world!';
console.log(endsWith(str, 'world!')); // true
console.log(endsWith(str, 'Hello')); // false
使用正则表达式
正则表达式也可以实现类似功能:
function endsWith(str, searchStr) {
const regex = new RegExp(searchStr + '$');
return regex.test(str);
}
const str = 'Hello, world!';
console.log(endsWith(str, 'world!')); // true
性能考虑
原生 endsWith 方法通常性能最优,手动实现适用于兼容性场景,正则表达式适合复杂匹配需求。






