js实现endwith
实现 JavaScript 的 endsWith 方法
JavaScript 本身提供了 String.prototype.endsWith() 方法,用于判断字符串是否以指定的子字符串结尾。如果需要手动实现类似功能,可以参考以下方法:
function customEndsWith(str, searchString, position) {
if (position === undefined || position > str.length) {
position = str.length;
}
position -= searchString.length;
return position >= 0 && str.indexOf(searchString, position) === position;
}
参数说明
str: 要检查的原字符串searchString: 要搜索的子字符串position(可选): 在字符串中搜索的位置,默认为字符串长度
使用示例
const str = "Hello, world!";
console.log(customEndsWith(str, "world!")); // true
console.log(customEndsWith(str, "World!")); // false
console.log(customEndsWith(str, "Hello", 5)); // true
兼容性处理
对于需要支持旧版 JavaScript 引擎的环境,可以添加以下 polyfill:
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(searchString, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) ||
Math.floor(position) !== position || position > subjectString.length) {
position = subjectString.length;
}
position -= searchString.length;
return position >= 0 && subjectString.indexOf(searchString, position) === position;
};
}
性能考虑
原生 endsWith 方法通常比手动实现的性能更好,因此在支持的环境中应优先使用原生方法。手动实现主要适用于需要兼容旧环境或特殊定制的场景。







