JavaScript判断字符串结尾的方法

在 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;
      };
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值