当前位置:首页 > JavaScript

js实现endwith

2026-01-31 21:17:21JavaScript

js实现endwith

实现 JavaScript 的 endsWith 方法

JavaScript 本身提供了 String.prototype.endsWith() 方法,用于判断字符串是否以指定的子字符串结尾。如果需要手动实现类似功能,可以参考以下方法:

js实现endwith

function customEndsWith(str, searchString, position) {
  if (position === undefined || position > str.length) {
    position = str.length;
  }
  position -= searchString.length;
  return position >= 0 && str.indexOf(searchString, position) === position;
}

参数说明

  • str: 要检查的原字符串
  • searchString: 要搜索的子字符串
  • position(可选): 在字符串中搜索的位置,默认为字符串长度

使用示例

const str = "Hello, world!";
console.log(customEndsWith(str, "world!"));  // true
console.log(customEndsWith(str, "World!"));  // false
console.log(customEndsWith(str, "Hello", 5));  // true

兼容性处理

对于需要支持旧版 JavaScript 引擎的环境,可以添加以下 polyfill:

if (!String.prototype.endsWith) {
  String.prototype.endsWith = function(searchString, position) {
    var subjectString = this.toString();
    if (typeof position !== 'number' || !isFinite(position) || 
        Math.floor(position) !== position || position > subjectString.length) {
      position = subjectString.length;
    }
    position -= searchString.length;
    return position >= 0 && subjectString.indexOf(searchString, position) === position;
  };
}

性能考虑

原生 endsWith 方法通常比手动实现的性能更好,因此在支持的环境中应优先使用原生方法。手动实现主要适用于需要兼容旧环境或特殊定制的场景。

标签: jsendwith
分享给朋友:

相关文章

js实现验证码

js实现验证码

实现验证码的JavaScript方法 生成随机验证码 使用Math.random()生成随机字符串,结合数字和字母: function generateCaptcha() { const cha…

js实现类

js实现类

JavaScript 实现类的几种方式 JavaScript 是一种基于原型的语言,但在 ES6 之后引入了 class 语法糖,使得实现类更加直观。以下是几种常见的实现方式: 使用构造函数 传统的…

节流js实现

节流js实现

节流(Throttle)的实现原理 节流是一种限制函数执行频率的技术,确保函数在一定时间间隔内最多执行一次。适用于高频触发事件(如滚动、输入、窗口调整等)的场景。 基础实现方式 使用时间戳判断是否执…

js实现代码雨

js实现代码雨

实现代码雨效果 使用HTML5 Canvas和JavaScript可以轻松实现经典的代码雨效果。以下是完整的实现代码和说明: HTML结构 <!DOCTYPE html> <…

js实现显示隐藏

js实现显示隐藏

显示隐藏的实现方法 在JavaScript中,实现元素的显示和隐藏可以通过多种方式完成。以下是几种常见的方法: 修改CSS的display属性 通过改变元素的display属性可以在none(隐藏)…

js实现定位

js实现定位

使用Geolocation API获取当前位置 在JavaScript中,可以通过浏览器内置的Geolocation API获取用户的地理位置信息。该API需要用户授权才能访问位置数据。 if (n…