当前位置:首页 > JavaScript

js endswith 实现

2026-01-31 17:22:05JavaScript

使用 String.prototype.endsWith()

JavaScript 的 String.prototype.endsWith() 方法可以直接判断字符串是否以指定的子字符串结尾。该方法返回布尔值。

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

可以指定搜索的结束位置:

console.log(str.endsWith('Hello', 5)); // true

手动实现 endsWith

如果需要在旧版 JavaScript 或特定场景中手动实现 endsWith,可以通过字符串截取和比较实现。

function customEndsWith(str, searchStr, position) {
  if (position === undefined || position > str.length) {
    position = str.length;
  }
  const start = position - searchStr.length;
  return start >= 0 && str.substring(start, position) === searchStr;
}

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

正则表达式实现

通过正则表达式也可以实现类似功能,但需要注意转义特殊字符。

js endswith 实现

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

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

性能考虑

原生 endsWith 方法通常性能最优,手动实现或正则表达式适用于特殊需求或兼容性场景。

标签: jsendswith
分享给朋友:

相关文章

js实现跳转

js实现跳转

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

js实现轮播

js实现轮播

实现轮播图的基本思路 轮播图的核心逻辑是通过定时切换展示的图片或内容,通常结合左右滑动按钮和指示器(小圆点)增强交互性。以下是基于原生JavaScript的实现方法。 HTML结构 构建轮播图的HT…

js实现图

js实现图

JavaScript 实现图的常用方法 在 JavaScript 中,图(Graph)可以通过多种方式实现,常见的包括邻接表(Adjacency List)和邻接矩阵(Adjacency Matrix…

js实现的游戏

js实现的游戏

JavaScript 游戏开发基础 JavaScript 是开发网页游戏的流行选择,因其无需插件即可在浏览器中运行。以下是一些关键技术和资源: HTML5 Canvas Canvas 提供了绘制图形…

js 实现截图

js 实现截图

使用html2canvas库实现截图 html2canvas是一个流行的JavaScript库,可将HTML元素转换为Canvas,进而导出为图片。 安装库: npm instal…

js实现上传图片预览

js实现上传图片预览

使用FileReader实现图片预览 通过FileReader对象读取用户选择的图片文件,并将其显示在页面上。这种方法适用于现代浏览器。 // HTML部分 <input type="file…