当前位置:首页 > JavaScript

js实现enfwith

2026-01-31 18:19:09JavaScript

在JavaScript中实现endsWith功能可以通过多种方式完成,包括使用原生字符串方法或自定义实现。以下是几种常见方法:

js实现enfwith

使用原生String.prototype.endsWith方法

ES6引入了原生方法String.prototype.endsWith,可直接判断字符串是否以指定子串结尾:

js实现enfwith

const str = 'Hello, world!';
console.log(str.endsWith('world!')); // true
console.log(str.endsWith('Hello')); // false

自定义实现endsWith

若需兼容旧环境或自定义逻辑,可通过以下方式实现:

function endsWith(str, searchStr, position) {
  if (position === undefined || position > str.length) {
    position = str.length;
  }
  return str.substring(position - searchStr.length, position) === searchStr;
}

console.log(endsWith('Hello, world!', 'world!')); // true

使用正则表达式

通过正则匹配字符串末尾模式:

function endsWithRegex(str, searchStr) {
  const regex = new RegExp(searchStr + '$');
  return regex.test(str);
}

console.log(endsWithRegex('Hello, world!', 'world!')); // true

性能注意事项

  • 原生endsWith性能最优,优先使用。
  • 自定义实现时注意处理position参数,避免越界。
  • 正则表达式适用于复杂匹配,但简单场景可能过度。

以上方法可根据实际需求选择,原生API为推荐方案。

标签: jsenfwith
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js实现倒计时

js实现倒计时

使用 setInterval 实现倒计时 通过 setInterval 定时器每秒更新剩余时间,适用于简单倒计时场景。 function countdown(seconds, callback) {…

js实现全选

js实现全选

实现全选功能的方法 在JavaScript中实现全选功能通常涉及监听全选复选框的点击事件,并根据其状态控制其他复选框的选中状态。以下是几种常见的实现方式: 基础DOM操作实现 通过获取所有目标复选框…

js分组实现

js分组实现

分组实现方法 在JavaScript中,可以通过多种方式实现数组或对象的分组操作。以下是几种常见的方法: 使用Array.prototype.reduce() 通过reduce方法可以轻松实现数组分…

jquery js

jquery js

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。它兼容多种浏览器,提供易于使用的 API,使开发者能够更高…

js树实现

js树实现

树的基本概念 树是一种非线性的数据结构,由节点和边组成。每个节点包含一个值和指向子节点的引用。树的顶部节点称为根节点,没有子节点的节点称为叶节点。 树的实现方式 在JavaScript中,树可以通过…