当前位置:首页 > JavaScript

js endswith 实现

2026-01-31 17:22:05JavaScript

使用 String.prototype.endsWith()

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

js endswith 实现

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

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

js endswith 实现

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

正则表达式实现

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

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

js实现文字滚动

js实现文字滚动

实现文字滚动的几种方法 使用CSS动画实现滚动 通过CSS的@keyframes和transform属性可以实现平滑的文字滚动效果。 <style> .scroll-text { w…

js实现路由

js实现路由

js实现路由的方法 在JavaScript中实现路由功能可以通过多种方式完成,以下是几种常见的方法: 使用原生JavaScript实现路由 通过监听window.onhashchange事件来实现基…

js实现 拖动

js实现 拖动

实现拖动的步骤 HTML 结构 创建一个可拖动的元素和一个放置区域: <div id="draggable" draggable="true">拖动我</div> <d…

js 实现文件上传

js 实现文件上传

文件上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现文件上传功能。以下是一个基础示例: <input ty…