当前位置:首页 > JavaScript

js endswith 实现

2026-03-02 08:30:28JavaScript

使用 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;
  };
}

js endswith 实现

标签: jsendswith
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。 // 方…

js实现选项卡

js实现选项卡

实现选项卡的基本思路 选项卡通常由一组标签和对应的内容面板组成。点击标签时,显示对应的内容面板,隐藏其他面板。实现这一效果需要结合HTML结构、CSS样式和JavaScript交互逻辑。 HTML结…

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('image…

js 实现链表

js 实现链表

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和指向下一个节点的指针。与数组不同,链表在内存中是非连续存储的,插入和删除操作效率较高。 链表的实现 在 JavaScrip…

js实现dh

js实现dh

JavaScript 实现 DH(Diffie-Hellman)密钥交换 Diffie-Hellman(DH)密钥交换是一种安全协议,允许双方在不安全的通信信道上建立一个共享密钥。以下是如何在 Jav…

js实现防洪

js实现防洪

防抖(Debounce)实现 防抖的核心思想是在事件触发后延迟执行回调函数,若在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口调整等场景。 function debounce(f…