JavaScript参考手册
字符串 | String
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 |
字符串 | String相关
JavaScript 是一种高级编程语言,通过解释执行,是一门动态类型,面向对象(基于原型)的解释型语言。它已经由ECMA(欧洲电脑制造商协会)通过 ECMAScript 实现语言的标准化。它被世界上的绝大多数网站所使用,也被世界主流浏览器( Chrome、IE、FireFox、Safari、Opera )支持。JavaScript 是一门基于原型、函数先行的语言,是一门多范式的语言,它支持面向对象编程,命令式编程,以及函数式编程。它提供语法来操控文本、数组、日期以及正则表达式等,不支持 I/O,比如网络