From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../global_objects/string/startswith/index.html | 97 ++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/startswith/index.html (limited to 'files/zh-cn/web/javascript/reference/global_objects/string/startswith') diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/startswith/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/startswith/index.html new file mode 100644 index 0000000000..2aaef9b688 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/startswith/index.html @@ -0,0 +1,97 @@ +--- +title: String.prototype.startsWith() +slug: Web/JavaScript/Reference/Global_Objects/String/startsWith +tags: + - JavaScript + - Prototype + - String + - 原型 + - 参考 + - 字符串 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/String/startsWith +--- +
{{JSRef}}
+ +

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

+ +
{{EmbedInteractiveExample("pages/js/string-startswith.html")}}
+ + + +

语法

+ +
str.startsWith(searchString[, position])
+ +

参数

+ +
+
searchString
+
要搜索的子字符串。
+
position {{optional_inline}}
+
str 中搜索 searchString 的开始位置,默认值为 0。
+
+ +

返回值

+ +

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

+ +

描述

+ +

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

+ +

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

+ +

示例

+ +

使用 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
+ +

规范

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}
+ +

浏览器兼容性

+ + + +

{{Compat("javascript.builtins.String.startsWith")}}

+ +

参见

+ + -- cgit v1.2.3-54-g00ecf