js endswith 实现
使用 String.prototype.endsWith()
JavaScript 的 String.prototype.endsWith() 方法可以直接判断字符串是否以指定的子字符串结尾。该方法区分大小写。
语法:
str.endsWith(searchString[, length])
searchString:需要匹配的子字符串。length(可选):指定字符串的长度,默认为原始字符串长度。
示例:
const str = 'Hello, world!';
console.log(str.endsWith('world!')); // true
console.log(str.endsWith('World!')); // false(大小写敏感)
console.log(str.endsWith('Hello', 5)); // true(指定长度为 5)
手动实现 endsWith
如果需要在没有原生支持的环境中实现类似功能,可以通过字符串截取或正则表达式实现。
方法 1:字符串截取比较
通过截取字符串末尾与目标字符串长度相同的部分进行比较。
function endsWith(str, searchString, length) {
if (length === undefined || length > str.length) {
length = str.length;
}
return str.substring(length - searchString.length, length) === searchString;
}
const str = 'Hello, world!';
console.log(endsWith(str, 'world!')); // true
console.log(endsWith(str, 'World!')); // false
console.log(endsWith(str, 'Hello', 5)); // true
方法 2:正则表达式
使用正则表达式匹配字符串末尾是否符合目标字符串。
function endsWith(str, searchString) {
const regex = new RegExp(searchString + '$');
return regex.test(str);
}
const str = 'Hello, world!';
console.log(endsWith(str, 'world!')); // true
console.log(endsWith(str, 'World!')); // false
性能比较
- 原生
endsWith()性能最佳,推荐优先使用。 - 字符串截取方法在简单场景下性能较好。
- 正则表达式方法灵活性高,但性能略低。
兼容性处理
如果需要兼容旧版本 JavaScript 环境,可以通过以下方式实现:
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(searchString, length) {
if (length === undefined || length > this.length) {
length = this.length;
}
return this.substring(length - searchString.length, length) === searchString;
};
}






