在 JavaScript 中,判断字符串是否以指定内容结尾有以下几种常用方法:
1. 使用 endsWith() 方法(ES6+ 推荐)
javascript
复制
下载
const str = "Hello, world!";
const suffix = "world!";
// 基本用法
console.log(str.endsWith(suffix)); // true
// 支持指定搜索长度(在指定长度内判断结尾)
console.log(str.endsWith("Hello", 5)); // true(前5个字符是 "Hello")
特点:
-
区分大小写:
"Hello".endsWith("hello")返回false -
兼容性:现代浏览器和 Node.js 均支持(IE 需转译或 Polyfill)
2. 使用 lastIndexOf()(兼容旧环境)
javascript
复制
下载
function endsWith(str, suffix) {
const startIndex = str.length - suffix.length;
return startIndex >= 0 && str.lastIndexOf(suffix) === startIndex;
}
// 使用示例
console.log(endsWith("Hello, world!", "world!")); // true
console.log(endsWith("Hello", "ello")); // true
特点:
-
兼容旧版 JavaScript(如 IE8+)
-
需手动处理边界情况(如
suffix比原字符串长)
3. 使用正则表达式 test()
javascript
复制
下载
const str = "Hello, world!";
const suffix = "world!";
// 动态生成正则(需转义特殊字符)
const regex = new RegExp(`${suffix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`);
console.log(regex.test(str)); // true
注意:
-
需要转义正则特殊字符(如
.、*等) -
性能不如
endsWith()
4. 手动截取比较(最基础方法)
javascript
复制
下载
const str = "Hello, world!";
const suffix = "world!";
function customEndsWith(str, suffix) {
if (suffix.length > str.length) return false;
const start = str.length - suffix.length;
return str.slice(start) === suffix;
}
console.log(customEndsWith(str, suffix)); // true
🔍 关键区别总结
| 方法 | 区分大小写 | 兼容性 | 是否支持指定长度 | 特殊字符处理 |
|---|---|---|---|---|
str.endsWith() | ✅ 是 | ES6+ | ✅ 是 | 无需处理 |
lastIndexOf() | ✅ 是 | 全浏览器 | ❌ 否 | 无需处理 |
正则 test() | ✅ 是 | 全浏览器 | ❌ 否 | 需转义 |
| 手动截取比较 | ✅ 是 | 全浏览器 | ❌ 否 | 无需处理 |
✅ 实际建议
-
现代项目:直接使用
endsWith()(简洁高效) -
兼容旧环境:结合 Polyfill 或
lastIndexOf()方案javascript
复制
下载
// endsWith 的 Polyfill if (!String.prototype.endsWith) { String.prototype.endsWith = function(suffix) { return this.slice(-suffix.length) === suffix; }; }



3309

被折叠的 条评论
为什么被折叠?



