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

string.startsWith

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

语法

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

参数

searchString要搜索的子字符串。

positionstr中搜索 searchString 的开始位置,默认值为 0,也就是真正的字符串开头处。

返回值

true如果在字符串的开头找到给定的字符; 否则,false

描述

这个方法可以让你确定一个字符串是否以另一个字符串开头。这种方法是区分大小写的。

示例

使用 startsWith()

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

console.log(str.startsWith('To be'));         // true
console.log(str.startsWith('not to be'));     // false
console.log(str.startsWith('not to be', 10)); // true

备注

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

代码语言:javascript
复制
if (!String.prototype.startsWith) {
    String.prototype.startsWith = function(searchString, position){
      return this.substr(position || 0, searchString.length) === searchString;
  };
}

A more robust and optimized Polyfill is available on GitHub by Mathias Bynens.

规范

Specification

Status

Comment

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

Standard

Initial definition.

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

Draft

浏览器兼容性

Feature

Chrome

Firefox

Edge

Internet Explorer

Opera

Safari

Basic Support

41

17

(Yes)

(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

扫码关注腾讯云开发者

领取腾讯云代金券