这篇翻译不完整。请帮忙从英语翻译这篇文章

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

语法

str.startsWith(searchString[, position])

参数

searchString
要搜索的子字符串。
position 可选
str 中搜索 searchString 的开始位置,默认值为 0,也就是真正的字符串开头处。

Return value

true if the given characters are found at the beginning of the string; otherwise, false.

Description

This method lets you determine whether or not a string begins with another string. This method is case-sensitive.

示例

使用 startsWith()

var str = "To be, or not to be, that is the question.";

alert(str.startsWith("To be"));         // true
alert(str.startsWith("not to be"));     // false
alert(str.startsWith("not to be", 10)); // true

Polyfill

此方法已被添加至 ECMAScript 2015 规范之中,但可能不能在所有的现行 JavaScript 实现中使用。不过,你可以用以下的代码段为 String.prototype.startsWith() 制作 Polyfill:

if (!String.prototype.startsWith) {
    Object.defineProperty(String.prototype, 'startsWith', {
        value: function(search, pos) {
            pos = !pos || pos < 0 ? 0 : +pos;
            return this.substring(pos, pos + search.length) === search;
        }
    });
}

Mathias Bynens 在 Github 上提供了一份更为稳定有效(完全符合 ES2015 规范),但性能略差、代码紧凑性微减的 PolyFill

规范

规范 状态 备注
ECMAScript 2015 (6th Edition, ECMA-262)
String.prototype.startsWith
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
String.prototype.startsWith
Draft  

浏览器兼容性

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
startsWithChrome Full support 41Edge Full support 12Firefox Full support 17IE No support NoOpera Full support 28Safari Full support 9WebView Android Full support YesChrome Android Full support 36Edge Mobile Full support YesFirefox Android Full support 17Opera Android Full support YesSafari iOS Full support 9Samsung Internet Android Full support Yesnodejs Full support 4.0.0
Full support 4.0.0
Full support 0.12
Disabled
Disabled From version 0.12: this feature is behind the --harmony runtime flag.

Legend

Full support  
Full support
No support  
No support
User must explicitly enable this feature.
User must explicitly enable this feature.

参见

文档标签和贡献者

最后编辑者: RainSlide,