当前位置:首页 > JavaScript

js endswith 实现

2026-03-02 08:30:28JavaScript

使用 String.prototype.endsWith()

JavaScript 的 String.prototype.endsWith() 方法可以直接判断字符串是否以指定的子字符串结尾。该方法区分大小写。

语法:

str.endsWith(searchString[, length])
  • searchString:需要匹配的子字符串。
  • length(可选):指定字符串的长度,默认为原始字符串长度。

示例:

js endswith 实现

const str = 'Hello, world!';
console.log(str.endsWith('world!')); // true
console.log(str.endsWith('World!')); // false(大小写敏感)
console.log(str.endsWith('Hello', 5)); // true(指定长度为 5)

手动实现 endsWith

如果需要在没有原生支持的环境中实现类似功能,可以通过字符串截取或正则表达式实现。

方法 1:字符串截取比较

通过截取字符串末尾与目标字符串长度相同的部分进行比较。

js endswith 实现

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

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

方法 2:正则表达式

使用正则表达式匹配字符串末尾是否符合目标字符串。

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

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

性能比较

  • 原生 endsWith() 性能最佳,推荐优先使用。
  • 字符串截取方法在简单场景下性能较好。
  • 正则表达式方法灵活性高,但性能略低。

兼容性处理

如果需要兼容旧版本 JavaScript 环境,可以通过以下方式实现:

if (!String.prototype.endsWith) {
  String.prototype.endsWith = function(searchString, length) {
    if (length === undefined || length > this.length) {
      length = this.length;
    }
    return this.substring(length - searchString.length, length) === searchString;
  };
}

标签: jsendswith
分享给朋友:

相关文章

js轮播图实现原理

js轮播图实现原理

轮播图的基本原理 轮播图通过动态切换显示的内容(图片、文本等)实现视觉上的滑动效果。核心原理是利用CSS和JavaScript控制元素的显示与隐藏,或通过变换位置实现滑动动画。 实现方法一:CSS…

js实现视口

js实现视口

js实现视口检测的方法 使用JavaScript检测元素是否进入视口(viewport)可以通过Intersection Observer API或手动计算元素位置实现。以下是两种常见方法: Int…

js 实现跳转

js 实现跳转

使用 window.location.href 进行跳转 通过修改 window.location.href 可以跳转到指定 URL,浏览器会加载新页面: window.location.hre…

js分页实现

js分页实现

分页的基本原理 分页的核心是通过计算当前页码和数据偏移量,从服务器或本地数据中截取对应范围的数据进行展示。通常需要以下参数:当前页码(currentPage)、每页条数(pageSize)、总数据量(…

js 实现图片 放大

js 实现图片 放大

使用 CSS transform 实现图片放大 通过 CSS 的 transform: scale() 属性可以实现图片的平滑放大效果。结合 JavaScript 监听鼠标事件控制放大状态: con…

js 实现按钮点击

js 实现按钮点击

实现按钮点击的 JavaScript 方法 HTML 按钮元素 在 HTML 中创建一个按钮,可以通过 <button> 或 <input> 标签实现: <button…