首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

string.endsWith

endsWith()方法用来判断当前字符串是否是以另外一个给定的子字符串“结尾”的,根据判断结果返回 truefalse

语法

代码语言:javascript
复制
str.endsWith(searchString[, length])

参数

searchString要搜索的子字符串。position在 str 中搜索 searchString 的结束位置,默认值为str.length,也就是真正的字符串结尾处。

返回值

如果给定的字符在string尾部找到,返回true 否则返回false.

描述

此方法可让您确定一个字符串是否以另一个字符串结尾。这种方法是区分大小写的。

示例

使用endsWith()

代码语言:javascript
复制
var str = 'To be, or not to be, that is the question.';

console.log(str.endsWith('question.')); // true
console.log(str.endsWith('to be'));     // false
console.log(str.endsWith('to be', 19)); // true

备注

此方法已被添加到ECMAScript 6规范中,可能尚未在所有JavaScript实现中提供。但是,您可以String.prototype.endsWith()使用以下代码片段进行填充:

代码语言:javascript
复制
if (!String.prototype.endsWith)
  String.prototype.endsWith = function(searchStr, Position) {
      // This works much better than >= because
      // it compensates for NaN:
      if (!(Position < this.length))
        Position = this.length;
      else
        Position |= 0; // round position
      return this.substr(Position - searchStr.length,
                         searchStr.length) === searchStr;
  };

规范

Specification

Status

Comment

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'String.prototype.endsWith' in that specification.

Standard

Initial definition.

ECMAScript Latest Draft (ECMA-262)The definition of 'String.prototype.endsWith' in that specification.

Living Standard

浏览器兼容性

Feature

Chrome

Edge

Firefox

Internet Explorer

Opera

Safari

Basic Support

41

(Yes)

17

No

28

9

Feature

Android

Chrome for Android

Edge mobile

Firefox for Android

IE mobile

Opera Android

iOS Safari

Basic Support

(Yes)

36

(Yes)

17

No

(Yes)

9

扫码关注腾讯云开发者

领取腾讯云代金券