string.startsWith
startsWith()方法用来判断当前字符串是否是以另外一个给定的子字符串“开头”的,根据判断结果返回true或false。
语法
str.startsWith(searchString[, position])参数
searchString要搜索的子字符串。
position在str中搜索 searchString 的开始位置,默认值为 0,也就是真正的字符串开头处。
返回值
true如果在字符串的开头找到给定的字符; 否则,false。
描述
这个方法可以让你确定一个字符串是否以另一个字符串开头。这种方法是区分大小写的。
示例
使用 startsWith()
//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()使用以下代码片段进行填充:
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 |
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com

