当前位置:首页 > JavaScript

js实现endwith

2026-01-31 21:17:21JavaScript

实现 JavaScript 的 endsWith 方法

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

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

js实现endwith

标签: jsendwith
分享给朋友:

相关文章

js实现轮播图

js实现轮播图

轮播图实现方法 基础HTML结构 <div class="slider"> <div class="slides"> <img src="image1.jpg…

vue.js实现轮播

vue.js实现轮播

Vue.js 实现轮播功能 使用第三方库(推荐) Vue.js 生态中有许多成熟的轮播组件库,例如 vue-awesome-swiper 或 swiper,它们功能丰富且易于集成。 安装 swipe…

js实现图片轮播

js实现图片轮播

实现基础图片轮播 使用HTML、CSS和JavaScript创建一个简单的图片轮播。HTML部分定义轮播容器和图片,CSS设置样式和动画效果,JavaScript处理轮播逻辑。 <div c…

js实现日历

js实现日历

实现日历的基本思路 使用JavaScript实现日历的核心是动态生成日期表格,并处理月份切换逻辑。需要计算当前月的天数、起始星期几,并动态渲染到页面上。 获取当前日期信息 通过Date对象获取当前…

js实现图片预览

js实现图片预览

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

js实现dh

js实现dh

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