js实现enfwith
在JavaScript中实现endsWith功能可以通过多种方式完成,包括使用原生字符串方法或自定义实现。以下是几种常见方法:
使用原生String.prototype.endsWith方法
ES6引入了原生方法String.prototype.endsWith,可直接判断字符串是否以指定子串结尾:
const str = 'Hello, world!';
console.log(str.endsWith('world!')); // true
console.log(str.endsWith('Hello')); // false
自定义实现endsWith
若需兼容旧环境或自定义逻辑,可通过以下方式实现:
function endsWith(str, searchStr, position) {
if (position === undefined || position > str.length) {
position = str.length;
}
return str.substring(position - searchStr.length, position) === searchStr;
}
console.log(endsWith('Hello, world!', 'world!')); // true
使用正则表达式
通过正则匹配字符串末尾模式:
function endsWithRegex(str, searchStr) {
const regex = new RegExp(searchStr + '$');
return regex.test(str);
}
console.log(endsWithRegex('Hello, world!', 'world!')); // true
性能注意事项
- 原生
endsWith性能最优,优先使用。 - 自定义实现时注意处理
position参数,避免越界。 - 正则表达式适用于复杂匹配,但简单场景可能过度。
以上方法可根据实际需求选择,原生API为推荐方案。







