js endswith 实现
使用 String.prototype.endsWith()
JavaScript 的 String.prototype.endsWith() 方法可以直接判断字符串是否以指定的子字符串结尾。该方法返回布尔值。

const str = 'Hello, world!';
console.log(str.endsWith('world!')); // true
console.log(str.endsWith('Hello')); // false
可以指定搜索的结束位置:

console.log(str.endsWith('Hello', 5)); // true
手动实现 endsWith
如果需要在旧版 JavaScript 或特定场景中手动实现 endsWith,可以通过字符串截取和比较实现。
function customEndsWith(str, searchStr, position) {
if (position === undefined || position > str.length) {
position = str.length;
}
const start = position - searchStr.length;
return start >= 0 && str.substring(start, position) === searchStr;
}
const str = 'Hello, world!';
console.log(customEndsWith(str, 'world!')); // true
console.log(customEndsWith(str, 'Hello', 5)); // true
正则表达式实现
通过正则表达式也可以实现类似功能,但需要注意转义特殊字符。
function regexEndsWith(str, searchStr) {
const regex = new RegExp(searchStr + '$');
return regex.test(str);
}
const str = 'Hello, world!';
console.log(regexEndsWith(str, 'world!')); // true
console.log(regexEndsWith(str, 'Hello')); // false
性能考虑
原生 endsWith 方法通常性能最优,手动实现或正则表达式适用于特殊需求或兼容性场景。






