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/@@iterator/index.html | 137 ++++++++ .../global_objects/string/anchor/index.html | 136 ++++++++ .../reference/global_objects/string/big/index.html | 123 +++++++ .../global_objects/string/blink/index.html | 119 +++++++ .../global_objects/string/bold/index.html | 119 +++++++ .../global_objects/string/charat/index.html | 280 ++++++++++++++++ .../global_objects/string/charcodeat/index.html | 161 ++++++++++ .../global_objects/string/codepointat/index.html | 173 ++++++++++ .../global_objects/string/concat/index.html | 83 +++++ .../global_objects/string/endswith/index.html | 98 ++++++ .../global_objects/string/fixed/index.html | 117 +++++++ .../global_objects/string/fontcolor/index.html | 141 ++++++++ .../global_objects/string/fontsize/index.html | 130 ++++++++ .../global_objects/string/fromcharcode/index.html | 91 ++++++ .../global_objects/string/fromcodepoint/index.html | 144 +++++++++ .../global_objects/string/includes/index.html | 111 +++++++ .../reference/global_objects/string/index.html | 357 +++++++++++++++++++++ .../global_objects/string/indexof/index.html | 181 +++++++++++ .../global_objects/string/italics/index.html | 109 +++++++ .../global_objects/string/lastindexof/index.html | 162 ++++++++++ .../global_objects/string/length/index.html | 135 ++++++++ .../global_objects/string/link/index.html | 76 +++++ .../global_objects/string/localecompare/index.html | 185 +++++++++++ .../global_objects/string/match/index.html | 215 +++++++++++++ .../global_objects/string/matchall/index.html | 135 ++++++++ .../global_objects/string/normalize/index.html | 231 +++++++++++++ .../global_objects/string/padend/index.html | 100 ++++++ .../global_objects/string/padstart/index.html | 102 ++++++ .../global_objects/string/prototype/index.html | 186 +++++++++++ .../global_objects/string/quote/index.html | 116 +++++++ .../reference/global_objects/string/raw/index.html | 113 +++++++ .../global_objects/string/repeat/index.html | 124 +++++++ .../global_objects/string/replace/index.html | 317 ++++++++++++++++++ .../global_objects/string/replaceall/index.html | 171 ++++++++++ .../global_objects/string/search/index.html | 87 +++++ .../global_objects/string/slice/index.html | 122 +++++++ .../global_objects/string/small/index.html | 119 +++++++ .../global_objects/string/split/index.html | 213 ++++++++++++ .../global_objects/string/startswith/index.html | 97 ++++++ .../global_objects/string/strike/index.html | 116 +++++++ .../reference/global_objects/string/sub/index.html | 119 +++++++ .../global_objects/string/substr/index.html | 166 ++++++++++ .../global_objects/string/substring/index.html | 194 +++++++++++ .../reference/global_objects/string/sup/index.html | 118 +++++++ .../string/tolocalelowercase/index.html | 145 +++++++++ .../string/tolocaleuppercase/index.html | 91 ++++++ .../global_objects/string/tolowercase/index.html | 136 ++++++++ .../global_objects/string/tosource/index.html | 91 ++++++ .../global_objects/string/tostring/index.html | 124 +++++++ .../global_objects/string/touppercase/index.html | 87 +++++ .../global_objects/string/trim/index.html | 103 ++++++ .../global_objects/string/trimleft/index.html | 122 +++++++ .../global_objects/string/trimright/index.html | 84 +++++ .../global_objects/string/valueof/index.html | 58 ++++ 54 files changed, 7570 insertions(+) create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/@@iterator/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/anchor/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/big/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/blink/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/bold/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/charat/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/charcodeat/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/codepointat/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/concat/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/endswith/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/fixed/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/fontcolor/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/fontsize/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/fromcharcode/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/fromcodepoint/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/includes/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/indexof/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/italics/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/lastindexof/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/length/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/link/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/localecompare/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/match/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/matchall/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/normalize/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/padend/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/padstart/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/prototype/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/quote/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/raw/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/repeat/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/replace/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/replaceall/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/search/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/slice/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/small/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/split/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/startswith/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/strike/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/sub/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/substr/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/substring/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/sup/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/tolocalelowercase/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/tolocaleuppercase/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/tolowercase/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/tosource/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/tostring/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/touppercase/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/trim/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/trimleft/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/trimright/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/valueof/index.html (limited to 'files/zh-cn/web/javascript/reference/global_objects/string') diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/@@iterator/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/@@iterator/index.html new file mode 100644 index 0000000000..8ea489430f --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/@@iterator/index.html @@ -0,0 +1,137 @@ +--- +title: 'String.prototype[@@iterator]()' +slug: Web/JavaScript/Reference/Global_Objects/String/@@iterator +translation_of: Web/JavaScript/Reference/Global_Objects/String/@@iterator +--- +
{{JSRef}}
+ +

[@@iterator]() 方法返回一个新的Iterator对象,它遍历字符串的代码点,返回每一个代码点的字符串值。

+ +

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

+ +

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

+ +

语法

+ +
string[Symbol.iterator]
+ +

返回值

+ +

一个新的Iterator对象。

+ +

示例

+ +

使用[@@iterator]()

+ +
var string = 'A\uD835\uDC68';
+
+var strIter = string[Symbol.iterator]();
+
+console.log(strIter.next().value); // "A"
+console.log(strIter.next().value); // "\uD835\uDC68"
+
+ +

通过 for..of 使用[@@iterator]()

+ +
var string = 'A\uD835\uDC68B\uD835\uDC69C\uD835\uDC6A';
+
+for (var v of string) {
+  console.log(v);
+}
+// "A"
+// "\uD835\uDC68"
+// "B"
+// "\uD835\uDC69"
+// "C"
+// "\uD835\uDC6A"
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-string.prototype-@@iterator', 'String.prototype[@@iterator]()')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-string.prototype-@@iterator', 'String.prototype[@@iterator]()')}}{{Spec2('ESDraft')}}
+ + + + + + + +
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支持{{CompatVersionUnknown}}{{CompatGeckoDesktop("36")}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支持{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile("36")}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] From Gecko 17 (Firefox 17 / Thunderbird 17 / SeaMonkey 2.14) to Gecko 26 (Firefox 26 / Thunderbird 26 / SeaMonkey 2.23 / Firefox OS 1.2) the iterator property was used (bug 907077), and from Gecko 27 to Gecko 35 the "@@iterator" placeholder was used. In Gecko 36 (Firefox 36 / Thunderbird 36 / SeaMonkey 2.33), the @@iterator symbol got implemented (bug 918828).

+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/anchor/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/anchor/index.html new file mode 100644 index 0000000000..0b3a4169cd --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/anchor/index.html @@ -0,0 +1,136 @@ +--- +title: String.prototype.anchor() +slug: Web/JavaScript/Reference/Global_Objects/String/anchor +tags: + - HTML + - JavaScript + - Method + - Prototype + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/anchor +--- +
{{JSRef("Global_Objects", "String")}}
+ +

概述

+ +
+

已废弃
+ 该特性已经从 Web 标准中删除,虽然一些浏览器目前仍然支持它,但也许会在未来的某个时间停止支持,请尽量不要使用该特性。

+
+ +

anchor() 方法创建一个 {{HTMLElement("a")}} HTML 锚元素,被用作超文本靶标(hypertext target)。

+ +

语法

+ +
str.anchor(name) 
+ +

参数

+ +
+
name
+
一个字符串,表示被创建的标签的 name 属性。
+
+ +

返回值

+ +

 包含 {{HTMLElement("a")}} HTML元素的一个字符串。

+ +

描述

+ +

使用 anchor 方法能够以编程方式在一个文档中创建和展现一个锚链接。

+ +

语法上来讲,字符串表示你想让用户看到的文本。name 字符串参数表示 {{HTMLElement("a")}} 元素的 name 属性。

+ +

使用 anchor 方法创建的锚点(anchors)将会成为 {{domxref("document.anchors")}} 数组的元素。

+ +

示例

+ +

例子:使用 anchor

+ +
var myString = "Table of Contents";
+
+document.body.innerHTML = myString.anchor("contents_anchor");
+ +

将会输出下面的 HTML:

+ +
<a name="contents_anchor">Table of Contents</a>
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('ES6', '#sec-string.prototype.anchor', 'String.prototype.anchor')}}{{Spec2('ES6')}}Initial definition. Implemented in JavaScript 1.0.
+ Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop("1.0") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatGeckoMobile("1.0") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Gecko-specific notes

+ +

从{{gecko("17")}}开始  " (引号) 被 HTML引用字符 &quot所替代;在字符串中申请命名参数.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/big/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/big/index.html new file mode 100644 index 0000000000..8854fd3b2b --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/big/index.html @@ -0,0 +1,123 @@ +--- +title: String.prototype.big() +slug: Web/JavaScript/Reference/Global_Objects/String/big +translation_of: Web/JavaScript/Reference/Global_Objects/String/big +--- +
{{JSRef}} {{deprecated_header}}
+ +

big()方法的作用是创建一个使字符串显示大号字体的{{HTMLElement("big")}}标签。

+ +
+

使用说明:  <big> 元素在HTML5中已经被移除了,不应该再使用它。 取而代之的是web开发人员应该使用CSS 属性。

+
+ +

语法

+ +
str.big()
+ +

返回值

+ +

带有 {{HTMLElement("big")}}标签的字符串。

+ +

描述

+ +

big() 方法会将一个字符串嵌入到<big>标签中: "<big>str</big>"。

+ +

示例

+ +

使用big()函数

+ +

下面的例子使用了字符串方法来改变一个字符串的字体大小:

+ +
var worldString = 'Hello, world';
+
+console.log(worldString.small());     // <small>Hello, world</small>
+console.log(worldString.big());       // <big>Hello, world</big>
+console.log(worldString.fontsize(7)); // <fontsize=7>Hello, world</fontsize>
+
+ +

使用 {{domxref("HTMLElement.style", "element.style")}} 对象,你能更加一般地获得和操作该元素的style属性,比如:

+ +
document.getElementById('yourElemId').style.fontSize = '2em';
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.big', 'String.prototype.big')}}{{Spec2('ES6')}}初始定义。 在JavaScript 1.0中实现。在(规范性)附件B中定义了用于Web浏览器的附加ECMAScript 特性。
{{SpecName('ESDraft', '#sec-string.prototype.big', 'String.prototype.big')}}{{Spec2('ESDraft')}}在(规范性)附件B中定义了用于Web浏览器的附加ECMAScript 特性。
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/blink/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/blink/index.html new file mode 100644 index 0000000000..88cdb9cbf8 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/blink/index.html @@ -0,0 +1,119 @@ +--- +title: String.prototype.blink() +slug: Web/JavaScript/Reference/Global_Objects/String/blink +translation_of: Web/JavaScript/Reference/Global_Objects/String/blink +--- +
{{JSRef}} {{deprecated_header}}
+ +

blink()方法创建使字符串闪烁的 {{HTMLElement("blink")}} HTML 元素。

+ +
+

警告:闪烁文本被多种普及标准否决。 <blink>元素自身是非标准的,并且已废弃!

+
+ +

语法

+ +
str.blink()
+ +

返回值

+ +

包含  {{HTMLElement("blink")}} HTML 元素的字符串。

+ +

描述

+ +

blink()方法将字符串嵌入 <blink> 标签中: "<blink>str</blink>".

+ +

示例

+ +

使用blink()函数

+ +

下面的示例使用了字符串方法来修改字符串格式:

+ +
var worldString = 'Hello, world';
+
+console.log(worldString.blink());   // <blink>Hello, world</blink>
+console.log(worldString.bold());    // <b>Hello, world</b>
+console.log(worldString.italics()); // <i>Hello, world</i>
+console.log(worldString.strike());  // <strike>Hello, world</strike>
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.blink', 'String.prototype.blink')}}{{Spec2('ES6')}}初始定义。在 JavaScript 1.0 中实现。 在(规范性)附件 B 中定义了用于 Web 浏览器的 ECMAScript 附加特性。
{{SpecName('ESDraft', '#sec-string.prototype.blink', 'String.prototype.blink')}}{{Spec2('ESDraft')}}在(规范性)附件 B 中定义了用于 Web 浏览器的 ECMAScript 附加特性。
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/bold/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/bold/index.html new file mode 100644 index 0000000000..1ff02a8d34 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/bold/index.html @@ -0,0 +1,119 @@ +--- +title: String.prototype.bold() +slug: Web/JavaScript/Reference/Global_Objects/String/bold +tags: + - Deprecated + - HTML wrapper methods + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/String/bold +--- +

{{JSRef}} {{deprecated_header}}

+ +

bold() 方法会创建 HTML 元素 “b”,并将字符串加粗展示。

+ +

语法

+ +
str.bold()
+ +

返回值

+ +

包含HTML元素 {{HTMLElement("b")}} 的字符串。

+ +

描述

+ +

bold() 方法将一个字符串嵌入到<b></b>标记中。

+ +

示例

+ +

使用bold()

+ +

下面的例子使用字符串方法来改变字符串的格式。

+ +
var worldString = 'Hello, world';
+
+console.log(worldString.blink());   // <blink>Hello, world</blink>
+console.log(worldString.bold());    // <b>Hello, world</b>
+console.log(worldString.italics()); // <i>Hello, world</i>
+console.log(worldString.strike());  // <strike>Hello, world</strike>
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.bold', 'String.prototype.bold')}}{{Spec2('ES6')}}Initial definition. Implemented in JavaScript 1.0. Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.
{{SpecName('ESDraft', '#sec-string.prototype.bold', 'String.prototype.bold')}}{{Spec2('ESDraft')}}Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

相关连接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/charat/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/charat/index.html new file mode 100644 index 0000000000..3ed7dd0e7b --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/charat/index.html @@ -0,0 +1,280 @@ +--- +title: String.prototype.charAt() +slug: Web/JavaScript/Reference/Global_Objects/String/charAt +tags: + - String.prototype.charAt() +translation_of: Web/JavaScript/Reference/Global_Objects/String/charAt +--- +

{{JSRef}}

+ +

概述

+ +

charAt() 方法从一个字符串中返回指定的字符。

+ +

语法

+ +
str.charAt(index)
+ +

参数

+ +
+
index
+
一个介于0 和字符串长度减1之间的整数。 (0~length-1)
+
如果没有提供索引,charAt() 将使用0。
+
 
+
+ +

描述

+ +

字符串中的字符从左向右索引,第一个字符的索引值为 0,最后一个字符(假设该字符位于字符串 stringName 中)的索引值为 stringName.length - 1。 如果指定的 index 值超出了该范围,则返回一个空字符串。

+ +

示例

+ +

例子:输出字符串中不同位置的字符

+ +

下例输出字符串 "Brave new world" 不同位置处的字符:

+ +
var anyString = "Brave new world";
+
+console.log("The character at index 0   is '" + anyString.charAt(0)   + "'");
+console.log("The character at index 1   is '" + anyString.charAt(1)   + "'");
+console.log("The character at index 2   is '" + anyString.charAt(2)   + "'");
+console.log("The character at index 3   is '" + anyString.charAt(3)   + "'");
+console.log("The character at index 4   is '" + anyString.charAt(4)   + "'");
+console.log("The character at index 999 is '" + anyString.charAt(999) + "'");
+
+ +

上面代码的输出为:

+ +
The character at index 0 is 'B'
+The character at index 1 is 'r'
+The character at index 2 is 'a'
+The character at index 3 is 'v'
+The character at index 4 is 'e'
+The character at index 999 is ''
+
+ +

例子:获取所有字符

+ +

以下提供了一种确保通过字符串循环总是提供整个字符的方法,即使该字符串包含不在基本多文种平面(BMP)中的字符。

+ +
var str = 'A \uD87E\uDC04 Z'; // We could also use a non-BMP character directly
+for (var i=0, chr; i < str.length; i++) {
+  if ((chr = getWholeChar(str, i)) === false) {
+    continue;
+  } // Adapt this line at the top of each loop, passing in the whole string and
+    // the current iteration and returning a variable to represent the
+    // individual character
+
+  alert(chr);
+}
+
+function getWholeChar (str, i) {
+  var code = str.charCodeAt(i);
+
+  if (isNaN(code)) {
+    return ''; // Position not found
+  }
+  if (code < 0xD800 || code > 0xDFFF) {
+    return str.charAt(i);
+  }
+
+  // High surrogate (could change last hex to 0xDB7F to treat high private
+  // surrogates as single characters)
+  if (0xD800 <= code && code <= 0xDBFF) {
+    if (str.length <= (i+1))  {
+      throw 'High surrogate without following low surrogate';
+    }
+    var next = str.charCodeAt(i+1);
+      if (0xDC00 > next || next > 0xDFFF) {
+        throw 'High surrogate without following low surrogate';
+      }
+      return str.charAt(i)+str.charAt(i+1);
+  }
+  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
+  if (i === 0) {
+    throw 'Low surrogate without preceding high surrogate';
+  }
+  var prev = str.charCodeAt(i-1);
+
+  // (could change last hex to 0xDB7F to treat high private
+  // surrogates as single characters)
+  if (0xD800 > prev || prev > 0xDBFF) {
+    throw 'Low surrogate without preceding high surrogate';
+  }
+  // We can pass over low surrogates now as the second component
+  // in a pair which we have already processed
+  return false;
+}
+
+
+ +

在允许解构分配的独占JavaScript 1.7+环境(如Firefox)中,以下是一个更简洁和更灵活的替代方法,它会自动递增一个递增变量(如果字符保证它是一个替代对)。

+ +
var str = 'A\uD87E\uDC04Z'; // We could also use a non-BMP character directly
+for (var i=0, chr; i < str.length; i++) {
+  [chr, i] = getWholeCharAndI(str, i);
+  // Adapt this line at the top of each loop, passing in the whole string and
+  // the current iteration and returning an array with the individual character
+  // and 'i' value (only changed if a surrogate pair)
+
+  alert(chr);
+}
+
+function getWholeCharAndI (str, i) {
+  var code = str.charCodeAt(i);
+
+  if (isNaN(code)) {
+    return ''; // Position not found
+  }
+  if (code < 0xD800 || code > 0xDFFF) {
+    return [str.charAt(i), i]; // Normal character, keeping 'i' the same
+  }
+
+  // High surrogate (could change last hex to 0xDB7F to treat high private
+  // surrogates as single characters)
+  if (0xD800 <= code && code <= 0xDBFF) {
+    if (str.length <= (i+1))  {
+      throw 'High surrogate without following low surrogate';
+    }
+    var next = str.charCodeAt(i+1);
+      if (0xDC00 > next || next > 0xDFFF) {
+        throw 'High surrogate without following low surrogate';
+      }
+      return [str.charAt(i)+str.charAt(i+1), i+1];
+  }
+  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
+  if (i === 0) {
+    throw 'Low surrogate without preceding high surrogate';
+  }
+  var prev = str.charCodeAt(i-1);
+
+  // (could change last hex to 0xDB7F to treat high private surrogates
+  // as single characters)
+  if (0xD800 > prev || prev > 0xDBFF) {
+    throw 'Low surrogate without preceding high surrogate';
+  }
+  // Return the next character instead (and increment)
+  return [str.charAt(i+1), i+1];
+}
+ +

示例:修复charAt以支持非基本多文种平面(BMP)字符

+ +

虽然上面的例子对于那些希望支持非BMP字符的用户可能更有用(因为它不要求调用者知道任何非BMP字符可能出现在哪里),在人们希望的情况下,在选择字符 通过索引,将字符串中的替代对作为它们表示的单个字符,可以使用以下:

+ +
function fixedCharAt (str, idx) {
+  var ret = '';
+  str += '';
+  var end = str.length;
+
+  var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
+  while ((surrogatePairs.exec(str)) != null) {
+    var li = surrogatePairs.lastIndex;
+    if (li - 2 < idx) {
+      idx++;
+    } else {
+      break;
+    }
+  }
+
+  if (idx >= end || idx < 0) {
+    return '';
+  }
+
+  ret += str.charAt(idx);
+
+  if (/[\uD800-\uDBFF]/.test(ret) && /[\uDC00-\uDFFF]/.test(str.charAt(idx+1))) {
+    // Go one further, since one of the "characters" is part of a surrogate pair
+    ret += str.charAt(idx+1);
+  }
+  return ret;
+}
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.5.4.4', 'String.prototype.charAt')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.charat', 'String.prototype.charAt')}}{{Spec2('ES6')}} 
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/charcodeat/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/charcodeat/index.html new file mode 100644 index 0000000000..2fa6e19305 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/charcodeat/index.html @@ -0,0 +1,161 @@ +--- +title: String.prototype.charCodeAt() +slug: Web/JavaScript/Reference/Global_Objects/String/charCodeAt +tags: + - JavaScript + - String + - Unicode + - 参考 + - 字符串 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/String/charCodeAt +--- +
{{JSRef}}
+ +

charCodeAt() 方法返回 065535 之间的整数,表示给定索引处的 UTF-16 代码单元

+ +
{{EmbedInteractiveExample("pages/js/string-charcodeat.html", "shorter")}}
+ + + +

UTF-16 编码单元匹配能用一个 UTF-16 编码单元表示的 Unicode 码点。如果 Unicode 码点不能用一个 UTF-16 编码单元表示(因为它的值大于0xFFFF),则所返回的编码单元会是这个码点代理对的第一个编码单元) 。如果你想要整个码点的值,使用 {{jsxref("Global_Objects/String/codePointAt", "codePointAt()")}}。

+ +

语法

+ +
str.charCodeAt(index)
+ +

参数

+ +
+
index
+
一个大于等于 0,小于字符串长度的整数。如果不是一个数值,则默认为 0
+
+ +

返回值

+ +

指定 index 处字符的 UTF-16 代码单元值的一个数字;如果 index 超出范围,charCodeAt() 返回 {{jsxref("Global_Objects/NaN", "NaN")}}。

+ +

描述

+ +

Unicode 码点(code points)的范围从 01114111 (0x10FFFF)。开头的 128 个 Unicode 编码单元和 ASCII 字符编码一样。(关于 Unicode 的更多信息,可查看 JavaScript Guide。)

+ +
+

注意:charCodeAt 总是返回一个小于 65,536 的值。这是因为高位编码单元(higher code point)使用一对(低位编码 lower valued)代理伪字符("surrogate" pseudo-characters)来表示,从而构成一个真正的字符。

+ +

因此,为了检查(或重现)65536 及以上编码字符的完整字符,需要在获取 charCodeAt(i) 的值的同时获取 charCodeAt(i+1) 的值(如同用两个字母操纵一个字符串),或者改为获取 codePointAt(i) 的值。参看下面例 2 和例 3。

+
+ +

如果指定的 index 小于 0 、等于或大于字符串的长度,则 charCodeAt 返回 {{jsxref("Global_Objects/NaN", "NaN")}}。

+ +

向后兼容:在历史版本中(如 JavaScript 1.2),charCodeAt 返回一个数字,表示给定 index 处字符的 ISO-Latin-1 编码值。ISO-Latin-1 编码集范围从 0255。开头的 0127 直接匹配 ASCII 字符集。

+ +

示例

+ +

使用 charCodeAt()

+ +

下例介绍了不同索引情况下返回的 Unicode 值:

+ +
"ABC".charCodeAt(0) // returns 65:"A"
+
+"ABC".charCodeAt(1) // returns 66:"B"
+
+"ABC".charCodeAt(2) // returns 67:"C"
+
+"ABC".charCodeAt(3) // returns NaN
+ +

使用 charCodeAt() 修复字符串中出现的未知的非基本多语言范围(非BMP,non-Basic-Multilingual-Plane)字符

+ +

这段代码可以被用在 for 循环和其他类似语句中,当在指定引索之前不确定是否有非BMP字符存在时。

+ +
function fixedCharCodeAt (str, idx) {
+    // ex. fixedCharCodeAt ('\uD800\uDC00', 0); // 65536
+    // ex. fixedCharCodeAt ('\uD800\uDC00', 1); // false
+    idx = idx || 0;
+    var code = str.charCodeAt(idx);
+    var hi, low;
+
+    // High surrogate (could change last hex to 0xDB7F to treat high
+    // private surrogates as single characters)
+    if (0xD800 <= code && code <= 0xDBFF) {
+        hi = code;
+        low = str.charCodeAt(idx+1);
+        if (isNaN(low)) {
+            throw 'High surrogate not followed by low surrogate in fixedCharCodeAt()';
+        }
+        return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
+    }
+    if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate
+        // We return false to allow loops to skip this iteration since should have
+        // already handled high surrogate above in the previous iteration
+        return false;
+        /*hi = str.charCodeAt(idx-1);
+        low = code;
+        return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;*/
+    }
+    return code;
+}
+
+ +

使用 charCodeAt() 修复字符串中出现的已知的非BMP字符

+ +
function knownCharCodeAt (str, idx) {
+    str += '';
+    var code,
+        end = str.length;
+
+    var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
+    while ((surrogatePairs.exec(str)) != null) {
+        var li = surrogatePairs.lastIndex;
+        if (li - 2 < idx) {
+            idx++;
+        }
+        else {
+            break;
+        }
+    }
+
+    if (idx >= end || idx < 0) {
+        return NaN;
+    }
+
+    code = str.charCodeAt(idx);
+
+    var hi, low;
+    if (0xD800 <= code && code <= 0xDBFF) {
+        hi = code;
+        low = str.charCodeAt(idx+1);
+        // Go one further, since one of the "characters" is part of a surrogate pair
+        return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
+    }
+    return code;
+}
+
+
+ +

规范

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

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/codepointat/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/codepointat/index.html new file mode 100644 index 0000000000..567de8abc1 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/codepointat/index.html @@ -0,0 +1,173 @@ +--- +title: String.prototype.codePointAt() +slug: Web/JavaScript/Reference/Global_Objects/String/codePointAt +translation_of: Web/JavaScript/Reference/Global_Objects/String/codePointAt +--- +
{{JSRef}}
+ +

codePointAt() 方法返回 一个 Unicode 编码点值的非负整数。

+ +

语法

+ +
str.codePointAt(pos)
+ +

参数

+ +
+
pos
+
这个字符串中需要转码的元素的位置。
+
+ +

返回值

+ +

返回值是在字符串中的给定索引的编码单元体现的数字,如果在索引处没找到元素则返回 {{jsxref("undefined")}} 。

+ +

描述

+ +

如果在指定的位置没有元素则返回 {{jsxref("undefined")}} 。如果在索引处开始没有UTF-16 代理对,将直接返回在那个索引处的编码单元。

+ +

Surrogate Pair是UTF-16中用于扩展字符而使用的编码方式,是一种采用四个字节(两个UTF-16编码)来表示一个字符,称作代理对。

+ +

例子

+ +

使用 codePointAt()

+ +
'ABC'.codePointAt(1);          // 66
+'\uD800\uDC00'.codePointAt(0); // 65536
+
+'XYZ'.codePointAt(42); // undefined
+
+ +

替补支持(Polyfill)

+ +

给原生不支持 ECMAScript 6 的浏览器使用codePointAt()方法的的一个字符串扩展方法。

+ +
/*! http://mths.be/codepointat v0.1.0 by @mathias */
+if (!String.prototype.codePointAt) {
+  (function() {
+    'use strict'; // 严格模式,needed to support `apply`/`call` with `undefined`/`null`
+    var codePointAt = function(position) {
+      if (this == null) {
+        throw TypeError();
+      }
+      var string = String(this);
+      var size = string.length;
+      // 变成整数
+      var index = position ? Number(position) : 0;
+      if (index != index) { // better `isNaN`
+        index = 0;
+      }
+      // 边界
+      if (index < 0 || index >= size) {
+        return undefined;
+      }
+      // 第一个编码单元
+      var first = string.charCodeAt(index);
+      var second;
+      if ( // 检查是否开始 surrogate pair
+        first >= 0xD800 && first <= 0xDBFF && // high surrogate
+        size > index + 1 // 下一个编码单元
+      ) {
+        second = string.charCodeAt(index + 1);
+        if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
+          // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
+          return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
+        }
+      }
+      return first;
+    };
+    if (Object.defineProperty) {
+      Object.defineProperty(String.prototype, 'codePointAt', {
+        'value': codePointAt,
+        'configurable': true,
+        'writable': true
+      });
+    } else {
+      String.prototype.codePointAt = codePointAt;
+    }
+  }());
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.codepointat', 'String.prototype.codePointAt')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-string.prototype.codepointat', 'String.prototype.codePointAt')}}{{Spec2('ESDraft')}} 
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支持{{CompatChrome("41")}}{{CompatGeckoDesktop("29")}}11{{CompatOpera("28")}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性AndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支持{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("29")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/concat/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/concat/index.html new file mode 100644 index 0000000000..ee2d8dd06d --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/concat/index.html @@ -0,0 +1,83 @@ +--- +title: String.prototype.concat() +slug: Web/JavaScript/Reference/Global_Objects/String/concat +tags: + - JavaScript + - Method + - Prototype + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/concat +--- +
{{JSRef}}
+ +

concat() 方法将一个或多个字符串与原字符串连接合并,形成一个新的字符串并返回。

+ +

语法

+ +
str.concat(str2, [, ...strN])
+ +

参数

+ +
+
str2 [, ...strN]
+
需要连接到 str 的字符串。
+
+ +

返回值

+ +

一个新的字符串,包含参数所提供的连接字符串。

+ +

描述

+ +

concat 方法将一个或多个字符串与原字符串连接合并,形成一个新的字符串并返回。 concat 方法并不影响原字符串。

+ +

如果参数不是字符串类型,它们在连接之前将会被转换成字符串。

+ +

性能

+ +

强烈建议使用赋值操作符+, +=)代替 concat 方法。

+ +

示例

+ +

使用 concat

+ +

下面的例子演示如何将多个字符串与原字符串合并为一个新字符串

+ +
let hello = 'Hello, '
+console.log(hello.concat('Kevin', '. Have a nice day.'))
+// Hello, Kevin. Have a nice day.
+
+let greetList = ['Hello', ' ', 'Venkat', '!']
+"".concat(...greetList)  // "Hello Venkat!"
+
+"".concat({})    // [object Object]
+"".concat([])    // ""
+"".concat(null)  // "null"
+"".concat(true)  // "true"
+"".concat(4, 5)  // "45"
+ +

规范

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

浏览器兼容性

+ +

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

+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/endswith/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/endswith/index.html new file mode 100644 index 0000000000..f7ed81e221 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/endswith/index.html @@ -0,0 +1,98 @@ +--- +title: String.prototype.endsWith() +slug: Web/JavaScript/Reference/Global_Objects/String/endsWith +tags: + - JavaScript + - Method + - Prototype + - Reference + - String + - 原型 + - 参考 + - 字符串 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/String/endsWith +--- +

{{JSRef}}

+ +

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

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

语法

+ +
str.endsWith(searchString[, length])
+ +

参数

+ +
+
searchString
+
要搜索的子字符串。
+
length {{optional_inline}}
+
作为 str 的长度。默认值为 str.length
+
+ +

返回值

+ +

如果传入的子字符串在搜索字符串的末尾则返回true;否则将返回 false

+ +

描述

+ +

这个方法帮助你确定一个字符串是否在另一个字符串的末尾。这个方法是大小写敏感的。

+ +

Polyfill

+ +

这个方法已经加入到 ECMAScript 6 标准当中,但是可能还没有在所有的  JavaScript 实现中可用。然而,你可以通过如下的代码片段扩展 String.prototype.endsWith() 实现兼容:

+ +
if (!String.prototype.endsWith) {
+	String.prototype.endsWith = function(search, this_len) {
+		if (this_len === undefined || this_len > this.length) {
+			this_len = this.length;
+		}
+		return this.substring(this_len - search.length, this_len) === search;
+	};
+}
+
+ +

示例

+ +

使用 endsWith()

+ +
var str = "To be, or not to be, that is the question.";
+
+alert( str.endsWith("question.") );  // true
+alert( str.endsWith("to be") );      // false
+alert( str.endsWith("to be", 19) );  // true
+
+ +

规范

+ + + + + + + + + + +
规范
{{SpecName('ESDraft', '#sec-string.prototype.endswith', 'String.prototype.endsWith')}}
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/fixed/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/fixed/index.html new file mode 100644 index 0000000000..f4af9c1103 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/fixed/index.html @@ -0,0 +1,117 @@ +--- +title: String.prototype.fixed() +slug: Web/JavaScript/Reference/Global_Objects/String/fixed +tags: + - Deprecated + - HTML wrapper methods + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/String/fixed +--- +
{{JSRef}} {{deprecated_header}}
+ +

fixed()方法创建了一个<tt>标签元素将字符串包裹起来,从而让这个字符串里面的内容具有固定间距。

+ +

语法

+ +
str.fixed()
+
+ +

Return value

+ +

返回一个表示 {{HTMLElement("tt")}} HTML 元素的字符串。

+ +

描述

+ +

fixed() 方法将一个字符串包裹在<tt></tt>标签中,比如: "<tt>str</tt>".

+ +

举例

+ +

使用fixed()

+ +

下面的示例代码使用这个fixed方法来改变字符串的格式:

+ +
var worldString = 'Hello, world';
+console.log(worldString.fixed()); // "<tt>Hello, world</tt>"
+
+ +

说明

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.fixed', 'String.prototype.fixed')}}{{Spec2('ES6')}}Initial definition. Implemented in JavaScript 1.0. Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.
{{SpecName('ESDraft', '#sec-string.prototype.fixed', 'String.prototype.fixed')}}{{Spec2('ESDraft')}}Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
版本ChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
版本AndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/fontcolor/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/fontcolor/index.html new file mode 100644 index 0000000000..1f9775194a --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/fontcolor/index.html @@ -0,0 +1,141 @@ +--- +title: String.prototype.fontcolor() +slug: Web/JavaScript/Reference/Global_Objects/String/fontcolor +tags: + - Deprecated + - HTML wrapper methods + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/fontcolor +--- +
{{JSRef}} {{deprecated_header}}
+ +

fontcolor()方法创建一个{{HTMLElement("font")}}的HTML元素让字符串被显示成指定的字体颜色。

+ +
+

使用注意:<font>元素已经在在HTML5中被移除并且不应该在使用。替代的是,web开发者应该使用CSS属性。

+
+ +

语法

+ +
str.fontcolor(color)
+ +

参数

+ +
+
color
+
代表颜色的一个字符串,可以是三个一组的十六进制的RGB值,也可以是一个颜色名称的字符串字面量,颜色名称的字符串字面量被列在了这里CSS颜色参考
+
+ +

返回值

+ +
+
一个包含一个{{HTMLElement("font")}} HTML元素的字符串。
+
+ +

描述

+ +

如果你表示的颜色为十六进制RGB三原色,则必须使用的格式rrggbb例如,对于橙红色的十六进制RGB值是红色=FA,绿色=80,和蓝=72,所以橙红色的RGB三原色"FA8072"

+ +

例子

+ +

使用 fontcolor()

+ +

下面的示例使用fontcolor()方法来改变字符串的颜色,通过产生一个被HTML <font> 标签包裹的字符串

+ +
var worldString = "Hello, world"
+
+console.log(worldString.fontcolor('red') + ' is red in this line');
+// <font color="red">Hello, world </font> is red in this line"
+
+console.log(worldString.fontcolor('FF00') + ' is red in hexadecimal'
+// <font color="FF00">Hello,world </font> is red in hexadecimal
+
+ +

和{{domxref("HTMLElement.style","element.style")}}对象一起,你可以访问元素的style属性,并且更随意的去操纵它,例如:

+ +
document.getElementById('yourElemId').style.color ='red';
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
规范状态评论
{{SpecName('ES6','#string.prototype.fontcolor', 'String.prototype.fontcolor')}}{{Spec2('ES6')}}初始定义。实现在JavaScript中1.0。定义为附加功能的ECMAScript针对Web浏览器(规范)附件B。
{{SpecName('ESDraft', '#string.prototype.fontcolor', 'String.prototype.fontcolor')}}{{Spec2('ESDraft')}}定义为附加功能的ECMAScript针对Web浏览器(规范)附件B。
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox(Gecko)Internet ExplorerOperaSafari
Basic Support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile(Gecko)IE MobileOpera MobileSafari Mobile
Basic Support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

也可以看看

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/fontsize/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/fontsize/index.html new file mode 100644 index 0000000000..676e1eff43 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/fontsize/index.html @@ -0,0 +1,130 @@ +--- +title: String.prototype.fontsize() +slug: Web/JavaScript/Reference/Global_Objects/String/fontsize +translation_of: Web/JavaScript/Reference/Global_Objects/String/fontsize +--- +
{{JSRef}} {{deprecated_header}}
+ +

The fontsize() method creates a {{HTMLElement("font")}} HTML element that causes a string to be displayed in the specified font size.

+ +
+

Usage note: The <font> element has been removed in HTML5 and shouldn't be used anymore. Instead web developers should use CSS properties.

+
+ +

语法

+ +
str.fontsize(size)
+ +

参数

+ +
+
size
+
An integer between 1 and 7, a string representing a signed integer between 1 and 7.
+
+ +

返回值

+ +

A string containing a {{HTMLElement("font")}} HTML element.

+ +

描述

+ +

When you specify size as an integer, you set the font size of str to one of the 7 defined sizes. When you specify size as a string such as "-2", you adjust the font size of str relative to the size set in the {{HTMLElement("basefont")}} tag.

+ +

示例

+ +

使用fontsize()方法

+ +

The following example uses string methods to change the size of a string:

+ +
var worldString = 'Hello, world';
+
+console.log(worldString.small());     // <small>Hello, world</small>
+console.log(worldString.big());       // <big>Hello, world</big>
+console.log(worldString.fontsize(7)); // <font size="7">Hello, world</fontsize>
+
+ +

With the {{domxref("HTMLElement.style", "element.style")}} object you can get the element's style attribute and manipulate it more generically, for example:

+ +
document.getElementById('yourElemId').style.fontSize = '0.7em';
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.fontsize', 'String.prototype.fontsize')}}{{Spec2('ES6')}}Initial definition. Implemented in JavaScript 1.0. Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.
{{SpecName('ESDraft', '#sec-string.prototype.fontsize', 'String.prototype.fontsize')}}{{Spec2('ESDraft')}}Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/fromcharcode/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/fromcharcode/index.html new file mode 100644 index 0000000000..fd399adab7 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/fromcharcode/index.html @@ -0,0 +1,91 @@ +--- +title: String.fromCharCode() +slug: Web/JavaScript/Reference/Global_Objects/String/fromCharCode +tags: + - ASCII码变成字符串 + - fromCharCode +translation_of: Web/JavaScript/Reference/Global_Objects/String/fromCharCode +--- +

{{JSRef}}

+ +

静态 String.fromCharCode() 方法返回由指定的 UTF-16 代码单元序列创建的字符串。

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

语法

+ +
String.fromCharCode(num1[, ...[, numN]])
+ +

参数

+ +
+
num1, ..., numN
+
一系列 UTF-16 代码单元的数字。范围介于 0655350xFFFF)之间。大于 0xFFFF 的数字将被截断。不进行有效性检查。
+
+ +

返回值

+ +

一个长度为 N 的字符串,由 N 个指定的 UTF-16 代码单元组成。

+ +

描述

+ +

该方法返回一个字符串,而不是一个  {{jsxref("String")}} 对象。

+ +

由于 fromCharCode() 是  {{jsxref("String")}} 的静态方法,所以应该像这样使用:String.fromCharCode(),而不是作为你创建的  {{jsxref("String")}} 对象的方法。

+ +

返回补充字符

+ +

在 UTF-16 中,绝大部分常用的字符可以用一个 16 位的值表示(即一个代码单元)。然而,有一类字符叫 Base Multilingual Plane (BMP),是所有可寻址的 Unicode 码点的 1/17th。剩下的码点,从范围 65536 (0x010000) 到 1114111 (0x10FFFF) 被称之为补充字符。在 UTF-16 中,补充字符也叫代理(surrogates),用两个 16 位代码单元表示,它是有目的被保留下来的。两个代理(surrogates)形成一个有效组合,也叫代理对,可以用来表示一个补充字符。

+ +

因为 fromCharCode() 只作用于 16 位的值 (跟 \u 转义序列一样),为了返回一个补充字符,一个代理对是必须的。例如,String.fromCharCode(0xD83C, 0xDF03)\uD83C\uDF03 返回码点 U+1F303 "Night with Stars"。

+ +

While there is a mathematical relationship between the supplementary code point value (e.g. 0x1F303) and both surrogate values that represent it (e.g., 0xD83C and 0xDF03), it does require an extra step to either calculate or look up the surrogate pair values every time a supplementary code point is to be used. 因此,使用 {{jsxref("String.fromCodePoint()")}} (ES2015 标准下的一个方法)更方便, 这个方法允许你基于真实的码点返回补充字符。例如 String.fromCodePoint(0x1F303) 返回码点 U+1F303 "Night with Stars"。

+ +

示例

+ +

使用 fromCharCode()

+ +

在 UTF-16 中,BMP 字符使用一个代码单元:

+ +
String.fromCharCode(65, 66, 67);   // 返回 "ABC"
+String.fromCharCode(0x2014);       // 返回 "—"
+String.fromCharCode(0x12014);      // 也是返回 "—"; 数字 1 被剔除并忽略
+String.fromCharCode(8212);         // 也是返回 "—"; 8212 是 0x2014 的十进制表示
+
+ +

完整的 UTF 16 表格.
+ 在 UTF-16 中,补充字符需要两个代码单元(即一个代理对):

+ +
String.fromCharCode(0xD83C, 0xDF03); // Code Point U+1F303 "Night with
+String.fromCharCode(55356, 57091);   // Stars" == "\uD83C\uDF03"
+
+String.fromCharCode(0xD834, 0xDF06, 0x61, 0xD834, 0xDF07); // "\uD834\uDF06a\uD834\uDF07"
+
+ +

规范

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-string.fromcharcode', 'String.fromCharCode')}}
+ +

浏览器兼容性

+ +

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

+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/fromcodepoint/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/fromcodepoint/index.html new file mode 100644 index 0000000000..786125e340 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/fromcodepoint/index.html @@ -0,0 +1,144 @@ +--- +title: String.fromCodePoint() +slug: Web/JavaScript/Reference/Global_Objects/String/fromCodePoint +translation_of: Web/JavaScript/Reference/Global_Objects/String/fromCodePoint +--- +
{{JSRef}}
+ +

String.fromCodePoint() 静态方法返回使用指定的代码点序列创建的字符串。

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

语法

+ +
String.fromCodePoint(num1[, ...[, numN]])
+ +

参数

+ +
+
num1, ..., numN
+
一串 Unicode 编码位置,即“代码点”。
+
+

返回值

+ +

使用指定的 Unicode 编码位置创建的字符串。

+
+
+ +

异常

+ +
+
{{jsxref("RangeError")}}
+
如果传入无效的 Unicode 编码,将会抛出一个{{jsxref("RangeError")}} (例如: "RangeError: NaN is not a valid code point")。
+
+ +

说明

+ +

该方法返回一个字符串,而不是一个 {{jsxref("String")}} 对象。

+ +

因为 fromCodePoint() 是 {{jsxref("String")}} 的一个静态方法,所以只能通过 String.fromCodePoint() 这样的方式来使用,不能在你创建的 {{jsxref("String")}} 对象实例上直接调用。

+ +

例子

+ +

使用 fromCodePoint()

+ +
String.fromCodePoint(42);       // "*"
+String.fromCodePoint(65, 90);   // "AZ"
+String.fromCodePoint(0x404);    // "\u0404"
+String.fromCodePoint(0x2F804);  // "\uD87E\uDC04"
+String.fromCodePoint(194564);   // "\uD87E\uDC04"
+String.fromCodePoint(0x1D306, 0x61, 0x1D307) // "\uD834\uDF06a\uD834\uDF07"
+
+String.fromCodePoint('_');      // RangeError
+String.fromCodePoint(Infinity); // RangeError
+String.fromCodePoint(-1);       // RangeError
+String.fromCodePoint(3.14);     // RangeError
+String.fromCodePoint(3e-2);     // RangeError
+String.fromCodePoint(NaN);      // RangeError
+
+ +
// String.fromCharCode() 方法不能单独获取在高代码点位上的字符
+// 另一方面,下列的示例中,可以返回 4 字节,也可以返回 2 字节的字符
+// (也就是说,它可以返回单独的字符,使用长度 2 代替 1!)
+console.log(String.fromCodePoint(0x2F804)); // or 194564 in decimal
+
+ +

Polyfill

+ +

String.fromCodePoint 方法是 ECMAScript2015(ES6)新增加的特性,所以一些老的浏览器可能还不支持。可以通过使用下面的 polyfill 代码来保证浏览器的支持:

+ +
if (!String.fromCodePoint) (function(stringFromCharCode) {
+    var fromCodePoint = function(_) {
+      var codeUnits = [], codeLen = 0, result = "";
+      for (var index=0, len = arguments.length; index !== len; ++index) {
+        var codePoint = +arguments[index];
+        // correctly handles all cases including `NaN`, `-Infinity`, `+Infinity`
+        // The surrounding `!(...)` is required to correctly handle `NaN` cases
+        // The (codePoint>>>0) === codePoint clause handles decimals and negatives
+        if (!(codePoint < 0x10FFFF && (codePoint>>>0) === codePoint))
+          throw RangeError("Invalid code point: " + codePoint);
+        if (codePoint <= 0xFFFF) { // BMP code point
+          codeLen = codeUnits.push(codePoint);
+        } else { // Astral code point; split in surrogate halves
+          // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
+          codePoint -= 0x10000;
+          codeLen = codeUnits.push(
+            (codePoint >> 10) + 0xD800,  // highSurrogate
+            (codePoint % 0x400) + 0xDC00 // lowSurrogate
+          );
+        }
+        if (codeLen >= 0x3fff) {
+          result += stringFromCharCode.apply(null, codeUnits);
+          codeUnits.length = 0;
+        }
+      }
+      return result + stringFromCharCode.apply(null, codeUnits);
+    };
+    try { // IE 8 only supports `Object.defineProperty` on DOM elements
+      Object.defineProperty(String, "fromCodePoint", {
+        "value": fromCodePoint, "configurable": true, "writable": true
+      });
+    } catch(e) {
+      String.fromCodePoint = fromCodePoint;
+    }
+}(String.fromCharCode));
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('ES2015', '#sec-string.fromcodepoint', 'String.fromCodePoint')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-string.fromcodepoint', 'String.fromCodePoint')}}{{Spec2('ESDraft')}} 
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/includes/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/includes/index.html new file mode 100644 index 0000000000..83ced4b38a --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/includes/index.html @@ -0,0 +1,111 @@ +--- +title: String.prototype.includes() +slug: Web/JavaScript/Reference/Global_Objects/String/includes +tags: + - JavaScript + - Method + - Monkey patching + - Prototype + - String + - String.prototype.includes() +translation_of: Web/JavaScript/Reference/Global_Objects/String/includes +--- +
{{JSRef}}
+ +

includes() 方法用于判断一个字符串是否包含在另一个字符串中,根据情况返回 true 或 false。

+ +

语法

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

参数

+ +
+
searchString
+
要在此字符串中搜索的字符串。
+
position {{optional_inline}}
+
从当前字符串的哪个索引位置开始搜寻子字符串,默认值为 0
+
+

返回值

+
+
如果当前字符串包含被搜寻的字符串,就返回 true;否则返回 false
+
+ +

描述

+ +

这个方法可以帮你判断一个字符串是否包含另外一个字符串。

+ +

区分大小写

+ +

includes() 方法是区分大小写的。例如,下面的表达式会返回 false

+ +
'Blue Whale'.includes('blue'); // returns false
+ +

兼容补丁

+ +

这个方法已经被加入到 ECMAScript 6 标准中,但未必在所有的 JavaScript 实现中都可以使用。然而,你可以轻松地 polyfill 这个方法:

+ +
if (!String.prototype.includes) {
+  String.prototype.includes = function(search, start) {
+    'use strict';
+    if (typeof start !== 'number') {
+      start = 0;
+    }
+
+    if (start + search.length > this.length) {
+      return false;
+    } else {
+      return this.indexOf(search, start) !== -1;
+    }
+  };
+}
+ +

示例

+ +

使用 includes()

+ +
var str = 'To be, or not to be, that is the question.';
+
+console.log(str.includes('To be'));       // true
+console.log(str.includes('question'));    // true
+console.log(str.includes('nonexistent')); // false
+console.log(str.includes('To be', 1));    // false
+console.log(str.includes('TO BE'));       // false
+ +

规范

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

浏览器兼容性

+ +

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

+ +

String.prototype.contains()

+ +

在 Firefox 18 - 39中,这个方法的名称叫 contains()。由于下面的理由,在{{bug(1102219)}}中,它被重命名为 includes() :

+ +

据报道,在Firefox 17上,一些使用 MooTools 1.2的网站会崩溃掉。这个版本的MooTools会检查函数 String.prototype.contains()  是否存在,如果不存在的话,MooTools就添加它自己的函数。通过在Firefox 17中引入这个函数,检查更改的行为在一定程度上导致了基于MooTools的 String.prototype.contains() 函数的代码实现中断。结果是,当 MooTools的拓展 导致 MooTools 1.2.6 版本的发布,此实现在Firefox 17中不可用和 String.prototype.contains() 在随后一个版本Firefox 18上是可用的。

+ +

MooTools 1.3会强制使用它自己版本的函数 String.prototype.contains(),因此,依赖它的网站不会崩溃掉。然而,你应该注意此方法在 MooTools 1.3 签名和ECMAScript 6 签名中的不同(在第二个参数)。后来,为了与ES6标准一致在MooTools 1.5版本及以上更改了签名

+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/index.html new file mode 100644 index 0000000000..d8b23c0904 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/index.html @@ -0,0 +1,357 @@ +--- +title: String +slug: Web/JavaScript/Reference/Global_Objects/String +tags: + - JavaScript + - String + - 参考 + - 字符串 +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +
{{JSRef}}
+ +

String 全局对象是一个用于字符串或一个字符序列的构造函数。

+ +

语法

+ +

字符串字面量采取以下形式:

+ +
'string text'
+"string text"
+"中文/汉语"
+"español"
+"English "
+"हिन्दी"
+"العربية"
+"português"
+"বাংলা"
+"русский"
+"日本語"
+"ਪੰਜਾਬੀ"
+"한국어"
+ +

你也能使用 String 函数将其他值生成或转换成字符串:

+ +
String(thing)
+new String(thing)
+ +

参数

+ +
+
thing
+
任何可以被转换成字符串的值。
+
+ +

模板字面量

+ +

从 ECMAScript 2015 开始,字符串字面量也可以称为模板字面量

+ +
`hello world` `hello! world!` `hello ${who}` escape `<a>${who}</a>`
+ +

转义字符

+ +
+
+ +

除了普通的可打印字符以外,一些有特殊功能的字符可以通过转义字符的形式放入字符串中:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CodeOutput
\0空字符
\'单引号
\"双引号
\\反斜杠
\n换行
\r回车
\v垂直制表符
\t水平制表符
\b退格
\f换页
\uXXXXunicode 码
\u{X} ... \u{XXXXXX}unicode codepoint {{experimental_inline}}
\xXXLatin-1 字符(x小写)
+ +
和其他语言不同,javascript 的字符串不区分单引号和双引号,所以不论是单引号还是双引号的字符串,上面的转义字符都能运行 。
+ +

长字符串

+ +

有时,你的代码可能含有很长的字符串。你可能想将这样的字符串写成多行,而不是让这一行无限延长或着被编辑器折叠。有两种方法可以做到这一点。

+ +

其一,可以使用 + 运算符将多个字符串连接起来,如下所示:

+ +
let longString = "This is a very long string which needs " +
+                 "to wrap across multiple lines because " +
+                 "otherwise my code is unreadable.";
+ +

其二,可以在每行末尾使用反斜杠字符(“\”),以指示字符串将在下一行继续。确保反斜杠后面没有空格或任何除换行符之外的字符或缩进; 否则反斜杠将不会工作。 如下所示:

+ +
let longString = "This is a very long string which needs \
+to wrap across multiple lines because \
+otherwise my code is unreadable.";
+ +

使用这两种方式会创建相同的字符串。

+ +
+
+ +

描述

+ +

字符串对于保存可以以文本形式表示的数据非常有用。 一些常用的字符串操作有:查询字符串长度,使用 + 和 += 运算符来构建和连接字符串,使用 indexOf 方法检查某一子字符串在父字符串中的位置,又或是使用 substring 方法提取从父字符串中提取子字符串。

+ +

从字符串中获取单个字符

+ +

获取字符串的某个字符有两种方法。 第一种是使用 {{jsxref("String.charAt", "charAt")}} 方法:

+ +
return 'cat'.charAt(1); // returns "a"
+
+ +

另一种 (在ECMAScript 5中有所介绍) 是把字符串当作一个类似数组的对象,其中的每个字符对应一个数值索引:

+ +
return 'cat'[1]; // returns "a"
+
+ +

使用括号访问字符串不可以对其进行删除或添加,因为字符串对应未知的属性并不是可读或配置的。 (更多的信息请参阅 {{jsxref("Object.defineProperty")}}。 )

+ +

字符串比较

+ +

熟练使用 C 语言的开发者经常使用 strcmp 函数来比较字符串,但在 JavaScript 中,你只需要使用比较操作符(>/</>=/<=)

+ +
var a = "a";
+var b = "b";
+if (a < b) // true
+  print(a + " is less than " + b);
+else if (a > b)
+  print(a + " is greater than " + b);
+else
+  print(a + " and " + b + " are equal.");
+
+ +

使用从字符串实例继承而来的 {{jsxref("String.localeCompare", "localeCompare")}} 方法也能达到同样的效果。 

+ +

基本字符串和字符串对象的区别

+ +

请注意区分 JavaScript 字符串对象和基本字符串值 . ( 对于 {{jsxref("Global_Objects/Boolean", "Boolean")}} 和{{jsxref("Global_Objects/Number", "Numbers")}} 也同样如此.)

+ +

字符串字面量 (通过单引号或双引号定义) 和 直接调用 String 方法(没有通过 new 生成字符串对象实例)的字符串都是基本字符串。JavaScript会自动将基本字符串转换为字符串对象,只有将基本字符串转化为字符串对象之后才可以使用字符串对象的方法。当基本字符串需要调用一个字符串对象才有的方法或者查询值的时候(基本字符串是没有这些方法的),JavaScript 会自动将基本字符串转化为字符串对象并且调用相应的方法或者执行查询。

+ +
var s_prim = "foo";
+var s_obj = new String(s_prim);
+
+console.log(typeof s_prim); // Logs "string"
+console.log(typeof s_obj);  // Logs "object"
+
+ +

当使用 {{jsxref("Global_Objects/eval", "eval")}}时,基本字符串和字符串对象也会产生不同的结果。eval 会将基本字符串作为源代码处理; 而字符串对象则被看作对象处理, 返回对象。 例如:

+ +
s1 = "2 + 2";               // creates a string primitive
+s2 = new String("2 + 2");   // creates a String object
+console.log(eval(s1));      // returns the number 4
+console.log(eval(s2));      // returns the string "2 + 2"
+
+ +

由于上述原因, 当一段代码在需要使用基本字符串的时候却使用了字符串对象就会导致执行失败(虽然一般情况下程序员们并不需要考虑这样的问题)。

+ +

利用 {{jsxref("String.valueOf", "valueOf")}} 方法,我们可以将字符串对象转换为其对应的基本字符串。

+ +
console.log(eval(s2.valueOf())); // returns the number 4
+
+ +
注意: 其他的将字符串对象转换成基本字符串的方法可以及参考 StringView – a C-like representation of strings based on typed arrays.
+ +

属性

+ +
+
{{jsxref("String.prototype")}}
+
可以为 String 对象增加新的属性。
+
+ +

方法

+ +
+
{{jsxref("String.fromCharCode()")}}  
+
 通过一串 Unicode 创建字符串。
+
+ +
+
{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}
+
通过一串 码点 创建字符串。
+
+ +
+
+
{{jsxref("String.raw()")}} {{experimental_inline}}
+
通过模板字符串创建字符串。
+
+
+ +

字符串泛型方法

+ +
+

字符串泛型是非标准的已弃用并且会在不远的将来删除。注意,你不能依靠他们的跨浏览器,而不使用下面提供的垫片。

+
+ +

应该避免在 Javascript 1.6 (Firefox 浏览器的 JS 引擎)中使用(虽然也支持)将其他对象转化为字符的方法,因为方法并没有成为 ECMA 标准:

+ +
let num = 15;
+console.log(String.replace(num, /5/, '2'));
+
+ +

移除字符串泛型的措施,参见 Warning: String.x is deprecated; use String.prototype.x instead.

+ +

{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}} 在 Javascript 1.6 中同样支持{{jsxref("Global_Objects/Array", "Array")}}。

+ +

String 实例

+ +

属性

+ +

{{page('zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}

+ +

{{page('zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods')}}

+ +

示例 

+ +

将其他值转换成字符串

+ +

使用 String() 方法将其它对象转化为字符串可以被认为是一种更加安全的做法,虽然该方法底层使用的也是 toString() 方法,但是针对 null/undefined/symbols,String() 方法会有特殊的处理:

+ +
var outputStrings = [];
+for (let i = 0, n = inputValues.length; i < n; ++i) {
+  outputStrings.push(String(inputValues[i]));
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string-objects', 'String')}}{{Spec2('ES6')}}
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support0.2{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/indexof/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/indexof/index.html new file mode 100644 index 0000000000..5bb7b532fc --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/indexof/index.html @@ -0,0 +1,181 @@ +--- +title: String.prototype.indexOf() +slug: Web/JavaScript/Reference/Global_Objects/String/indexOf +tags: + - JavaScript + - String + - 原型 + - 参考 + - 字符串 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf +--- +
{{JSRef}}
+ +

indexOf() 方法返回调用它的 {{jsxref("String")}} 对象中第一次出现的指定值的索引,从 fromIndex 处进行搜索。如果未找到该值,则返回 -1。

+ +
{{EmbedInteractiveExample("pages/js/string-indexof.html")}}
+ + + +
Note: For the Array method, see {{jsxref("Array.prototype.indexOf()")}}.
+ +

语法

+ +
str.indexOf(searchValue [, fromIndex])
+ +

参数

+ +
+
searchValue
+
要被查找的字符串值。
+
如果没有提供确切地提供字符串,searchValue 会被强制设置为 "undefined", 然后在当前字符串中查找这个值。
+
举个例子:'undefined'.indexOf() 将会返回0,因为 undefined 在位置0处被找到,但是 'undefine'.indexOf() 将会返回 -1 ,因为字符串 'undefined' 未被找到。
+
fromIndex {{optional_inline}}
+
数字表示开始查找的位置。可以是任意整数,默认值为 0
+
如果 fromIndex 的值小于 0,或者大于 str.length ,那么查找分别从 0 和str.length 开始。(译者注:  fromIndex 的值小于 0,等同于为空情况; fromIndex 的值大于或等于 str.length ,那么结果会直接返回 -1 。)
+
举个例子,'hello world'.indexOf('o', -5) 返回 4 ,因为它是从位置0处开始查找,然后 o 在位置4处被找到。另一方面,'hello world'.indexOf('o', 11) (或 fromIndex 填入任何大于11的值)将会返回 -1 ,因为开始查找的位置11处,已经是这个字符串的结尾了。
+
+ +

返回值

+ +

查找的字符串 searchValue 的第一次出现的索引,如果没有找到,则返回 -1

+ +

若被查找的字符串 searchValue 是一个空字符串,将会产生“奇怪”的结果。如果 fromIndex 值为空,或者 fromIndex 值小于被查找的字符串的长度,返回值和以下的 fromIndex 值一样:

+ +
'hello world'.indexOf('') // 返回 0
+'hello world'.indexOf('', 0) // 返回 0
+'hello world'.indexOf('', 3) // 返回 3
+'hello world'.indexOf('', 8) // 返回 8
+ +

另外,如果 fromIndex 值大于等于字符串的长度,将会直接返回字符串的长度(str.length):

+ +
'hello world'.indexOf('', 11) // 返回 11
+'hello world'.indexOf('', 13) // 返回 11
+'hello world'.indexOf('', 22) // 返回 11
+ +

从前面一个例子可以看出,被查找的值是空值时,Javascript将直接返回指定的索引值。从后面一个例子可以看出,被查找的值是空值时,Javascript将直接返回字符串的长度。

+ +

描述

+ +

字符串中的字符被从左向右索引。第一个字符的索引(index)是 0,变量名为 stringName 的字符串的最后一个字符的索引是 stringName.length - 1 。

+ +
"Blue Whale".indexOf("Blue")       // 返回 0
+"Blue Whale".indexOf("Blute")      // 返回 -1
+"Blue Whale".indexOf("Whale", 0)   // 返回 5
+"Blue Whale".indexOf("Whale", 5)   // 返回 5
+"Blue Whale".indexOf("", -1)       // 返回 0
+"Blue Whale".indexOf("", 9)        // 返回 9
+"Blue Whale".indexOf("", 10)       // 返回 10
+"Blue Whale".indexOf("", 11)       // 返回 10
+ +

indexOf 方法是区分大小写的。例如,下面的表达式将返回 -1

+ +
"Blue Whale".indexOf("blue")      // 返回 -1
+
+ +

检测是否存在某字符串

+ +

注意 0 并不会被当成 true-1 不会被当成 false 。所以当检测某个字符串是否存在于另一个字符串中时,可使用下面的方法:

+ +
'Blue Whale'.indexOf('Blue') !== -1    // true
+'Blue Whale'.indexOf('Bloe') !== -1    // false
+~('Blue Whale'.indexOf('Bloe'))        // 0, 这是一种错误用法
+ +

示例

+ +

使用indexOf() 和 lastIndexOf()

+ +

下例使用 indexOf()lastIndexOf() 方法定位字符串中 "Brave new world" 的值。

+ +
var anyString = "Brave new world";
+
+console.log("The index of the first w from the beginning is " + anyString.indexOf("w"));
+// logs 8
+console.log("The index of the first w from the end is " + anyString.lastIndexOf("w"));
+// logs 10
+
+console.log("The index of 'new' from the beginning is " + anyString.indexOf("new"));
+// logs 6
+console.log("The index of 'new' from the end is " + anyString.lastIndexOf("new"));
+// logs 6
+
+ +

indexOf 和区分大小写

+ +

下例定义了两个字符串变量。两个变量包含相同的字符串,除了第二个字符串中的某些字符为大写。第一个 log 方法输出 19。但是由于 indexOf 方法区分大小写,因此不会在 myCapString 中发现字符串 “cheddar",所以,第二个 log 方法会输出 -1。

+ +
var myString    = "brie, pepper jack, cheddar";
+var myCapString = "Brie, Pepper Jack, Cheddar";
+
+console.log('myString.indexOf("cheddar") is ' + myString.indexOf("cheddar"));
+// logs 19
+console.log('myCapString.indexOf("cheddar") is ' + myCapString.indexOf("cheddar"));
+// logs -1
+ +

使用 indexOf 统计一个字符串中某个字母出现的次数

+ +

在下例中,设置了 count 来记录字母 e 在字符串 str 中出现的次数:

+ +
// 翻译:生存还是毁灭?这是个问题。(莎士比亚《哈姆雷特》)
+var str = 'To be, or not to be, that is the question.';
+var count = 0;
+var pos = str.indexOf('e');
+
+while (pos !== -1) {
+  count++;
+  pos = str.indexOf('e', pos + 1);
+}
+
+console.log(count); // displays 4
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态说明
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5.4.7', 'String.prototype.indexOf')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ESDraft')}}
+ +

浏览器兼容性

+ + + +

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

+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/italics/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/italics/index.html new file mode 100644 index 0000000000..80ee07eabc --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/italics/index.html @@ -0,0 +1,109 @@ +--- +title: String.prototype.italics() +slug: Web/JavaScript/Reference/Global_Objects/String/italics +translation_of: Web/JavaScript/Reference/Global_Objects/String/italics +--- +
{{JSRef}} {{deprecated_header}}
+ +

The italics() method creates an {{HTMLElement("i")}} HTML element that causes a string to be italic.

+ +

Syntax

+ +
str.italics()
+ +

Description

+ +

The italics() method embeds a string in an <i> tag: "<i>str</i>".

+ +

Examples

+ +

Using italics()

+ +

The following example uses string methods to change the formatting of a string:

+ +
var worldString = 'Hello, world'; console.log(worldString.blink());  // Hello, world
+console.log(worldString.bold());  // Hello, world
+console.log(worldString.italics()); //Hello, world
+console.log(worldString.strike());  // Hello, world
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.italics', 'String.prototype.italics')}}{{Spec2('ES6')}}Initial definition. Implemented in JavaScript 1.0. Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.
{{SpecName('ESDraft', '#sec-string.prototype.italics', 'String.prototype.italics')}}{{Spec2('ESDraft')}}Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/lastindexof/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/lastindexof/index.html new file mode 100644 index 0000000000..5dca3e48d4 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/lastindexof/index.html @@ -0,0 +1,162 @@ +--- +title: String.prototype.lastIndexOf() +slug: Web/JavaScript/Reference/Global_Objects/String/lastIndexOf +translation_of: Web/JavaScript/Reference/Global_Objects/String/lastIndexOf +--- +

 {{JSRef}}

+ +

 lastIndexOf() 方法返回调用{{jsxref("String")}} 对象的指定值最后一次出现的索引,在一个字符串中的指定位置 fromIndex处从后向前搜索。如果没找到这个特定值则返回-1 。

+ +

该方法将从尾到头地检索字符串 str,看它是否含有子串 searchValue。开始检索的位置在字符串的 fromIndex 处或字符串的结尾(没有指定 fromIndex 时)。如果找到一个 searchValue,则返回 searchValue 的第一个字符在 str 中的位置。str中的字符位置是从 0 开始的。

+ +

语法

+ +
str.lastIndexOf(searchValue[, fromIndex])
+ +

参数

+ +
+
searchValue
+
一个字符串,表示被查找的值。如果searchValue是空字符串,则返回fromIndex
+
fromIndex{{optional_inline}}
+
待匹配字符串searchValue的开头一位字符从 str的第fromIndex位开始向左回向查找。fromIndex默认值是 +Infinity。如果 fromIndex >= str.length ,则会搜索整个字符串。如果 fromIndex < 0 ,则等同于 fromIndex == 0
+
+

返回值

+
+
+ +

返回指定值最后一次出现的索引(该索引仍是以从左至右0开始记数的),如果没找到则返回-1。

+ +

描述

+ +

字符串中的字符被从左向右索引。首字符的索引(index)是 0,最后一个字符的索引是 stringName.length - 1

+ +
'canal'.lastIndexOf('a');     // returns 3 (没有指明fromIndex则从末尾l处开始反向检索到的第一个a出现在l的后面,即index为3的位置)
+'canal'.lastIndexOf('a', 2);  // returns 1(指明fromIndex为2则从n处反向向回检索到其后面就是a,即index为1的位置)
+'canal'.lastIndexOf('a', 0);  // returns -1(指明fromIndex为0则从c处向左回向检索a发现没有,故返回-1)
+'canal'.lastIndexOf('x');     // returns -1
+'canal'.lastIndexOf('c', -5); // returns 0(指明fromIndex为-5则视同0,从c处向左回向查找发现自己就是,故返回0)
+'canal'.lastIndexOf('c', 0);  // returns 0(指明fromIndex为0则从c处向左回向查找c发现自己就是,故返回自己的索引0)
+'canal'.lastIndexOf('');      // returns 5
+'canal'.lastIndexOf('', 2);   // returns 2
+
+ +
+

Note: 'abab'.lastIndexOf('ab', 2) 将返回 2 而不是 0, 因为fromIndex只限制待匹配字符串的开头。

+
+ +

(例如'abadefgabm'.lastIndexOf('ab', 7) 返回7,虽然查找的'ab'中的b已经在 index=8的位置了从index=7的a处向左查找仍是能找到自身a加上其后连成ab,因为fromIndex指的是待匹配字符串的开头那一个)

+ +

区分大小写

+ +

lastIndexOf 方法区分大小写。例如,下面的表达式返回 -1:

+ +
"Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1
+ +

示例

+ +

例子:使用 indexOflastIndexOf

+ +

下例使用 indexOf 和 lastIndexOf 方法来定位字符串 "Brave new world" 中的值。

+ +
var anyString = "Brave new world";
+
+console.log("The index of the first w from the beginning is " + anyString.indexOf("w"));
+// Displays 8
+console.log("The index of the first w from the end is " + anyString.lastIndexOf("w"));
+// Displays 10
+
+console.log("The index of 'new' from the beginning is " + anyString.indexOf("new"));
+// Displays 6
+console.log("The index of 'new' from the end is " + anyString.lastIndexOf("new"));
+// Displays 6
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5.4.8', 'String.prototype.lastIndexOf')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.lastindexof', 'String.prototype.lastIndexOf')}}{{Spec2('ES6')}}
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/length/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/length/index.html new file mode 100644 index 0000000000..c51f812f6d --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/length/index.html @@ -0,0 +1,135 @@ +--- +title: String.length +slug: Web/JavaScript/Reference/Global_Objects/String/length +tags: + - JavaScript + - Property + - Prototype + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/length +--- +

{{JSRef("Global_Objects", "String")}}

+ +

概述

+ +

length 属性表示一个字符串的长度。

+ +

描述

+ +

该属性返回字符串中字符编码单元的数量。JavaScript 使用 {{ interwiki("wikipedia", "UTF-16") }} 编码,该编码使用一个 16 比特的编码单元来表示大部分常见的字符,使用两个代码单元表示不常用的字符。因此 length 返回值可能与字符串中实际的字符数量不相同。

+ +

空字符串的 length 为 0。

+ +

静态属性 String.length 返回 1。

+ +

示例

+ +
var x = "Mozilla";
+var empty = "";
+
+console.log("Mozilla is " + x.length + " code units long");
+/* "Mozilla is 7 code units long" */
+
+console.log("The empty string is has a length of " + empty.length);
+/* "The empty string is has a length of 0" */
+ +
 
+ +
 
+ +
 
+ +
 
+ +
 
+ +
 
+ +
 
+ +
 
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.5.1', 'String.prototype.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}{{Spec2('ES6')}} 
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/link/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/link/index.html new file mode 100644 index 0000000000..a3956f9ba7 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/link/index.html @@ -0,0 +1,76 @@ +--- +title: String.prototype.link() +slug: Web/JavaScript/Reference/Global_Objects/String/link +translation_of: Web/JavaScript/Reference/Global_Objects/String/link +--- +
{{JSRef}} {{deprecated_header}}
+ +

link() 方法创建一个 HTML 元素 {{HTMLElement("a")}} ,用该字符串作为超链接的显示文本,参数作为指向另一个 URL 的超链接。

+ +

语法

+ +
str.link(url)
+ +

参数

+ +
+
url
+
任何能够指定 a 标签的 href 属性的字符串;它应当是有效的 URL(相对或绝对),任何 & 字符将会被转义为 &amp;,任何 " 字符将会被转义为 &quot;
+
+ +

返回值

+ +

一个带有一个 HTML 元素 {{HTMLElement("a")}} 的字符串。

+ +

描述

+ +

使用 link 方法创建一个超链接 HTML 片段。返回的字符串可以通过 {{ Domxref("document.write") }} 或 {{ Domxref("element.innerHTML") }} 方法添加到文档中。

+ +

使用 link 方法创建的链接将会成为 document.links 数组中的元素。查看 {{ Domxref("document.links") }}。

+ +

示例

+ + + +

下例显示一个单词 "MDN" 作为超链接,指向 Mozilla Developer Network。

+ +
var hotText = 'MDN';
+var URL = 'https://developer.mozilla.org/';
+
+document.write('Click to return to ' + hotText.link(URL));
+// Click to return to <a href="https://developer.mozilla.org/">MDN</a>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.link', 'String.prototype.link')}}{{Spec2('ES6')}}Initial definition. Implemented in JavaScript 1.0. Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.
{{SpecName('ESDraft', '#sec-string.prototype.link', 'String.prototype.link')}}{{Spec2('ESDraft')}}Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/localecompare/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/localecompare/index.html new file mode 100644 index 0000000000..b3607222de --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/localecompare/index.html @@ -0,0 +1,185 @@ +--- +title: String.prototype.localeCompare() +slug: Web/JavaScript/Reference/Global_Objects/String/localeCompare +tags: + - Internationalization + - JavaScript + - String.prototype.localeCompare() + - 原型 + - 参考 + - 字符串 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/String/localeCompare +--- +
{{JSRef}}
+ +

localeCompare() 方法返回一个数字来指示一个参考字符串是否在排序顺序前面或之后或与给定字符串相同。

+ +

新的 locales 、 options 参数能让应用程序定制函数的行为即指定用来排序的语言。  localesoptions 参数是依赖于具体实现的,在旧的实现中这两个参数是完全被忽略的。

+ +

语法

+ +
referenceStr.localeCompare(compareString[, locales[, options]])
+ +

参数

+ +

查阅浏览器支持部分来确定哪些浏览器支持 locales 参数和 options 参数, 在功能检测中检查对 localesoptions 参数的支持

+ +
+
compareString
+
用来比较的字符串
+
locales
+
可选。 用来表示一种或多种语言或区域的一个符合 BCP 47 标准的字符串或一个字符串数组。 locales参数的一般形式与解释, 详情请参考 Intl page。 下列的 Unicode 扩展关键词是允许的:
+
co
+
为了某些地域多样的排序规则。可能的值包括: "big5han""dict""direct""ducet""gb2312""phonebk""phonetic""pinyin""reformed""searchjl""stroke""trad""unihan"。 "standard" 和"search" 这两个值是被忽略的; 它们被 options 的属性 usage 代替(往下看)。
+
kn
+
指定数值排序是否应该被使用, 像是这样 "1" < "2" < "10"。 可能的值是 "true" 和 "false"。 这个选项能被通过options 属性设置或通过 Unicode 扩展。 假如两个都被设置了, 则 options 优先。("language-region-u-kn-true|false")
+
kf
+
指定是否优先对大写字母或小写字母排序。 可能的值有 "upper""lower", 或 "false" (use the locale's default)。这个选项能被通过options 属性设置或通过 Unicode 扩展。假如两个都被设置了, 则 options 优先。("language-region-u-kf-upper|lower|false")
+
options
+
+

可选。 支持下列的一些或全部属性的一个对象:

+ +
+
localeMatcher
+
地域匹配算法的使用. 可能的值是 "lookup" 和 "best fit"; 默认的值是 "best fit"。更多相关的资料, 请参考 Intl page.
+
usage
+
指定比较的目标是排序或者是搜索. 可能的值是 "sort" 和 "search"; 默认是 "sort".
+
sensitivity
+
+

指定排序程序的敏感度(Which differences in the strings should lead to non-zero result values.) 可能的有:

+ +
    +
  • "base": 只有不同的字母字符串比较是不相等的. 举个例子: a ≠ ba = áa = A.
  • +
  • "accent": 只有不同的字母或读音比较是不相等的. 举个例子: a ≠ ba ≠ áa = A.
  • +
  • "case": 只有不同的字母或大小写比较是不相等的. 举个例子: a ≠ ba = áa ≠ A.
  • +
  • "variant": 不同的字母或读音及其它有区别的标志或大小写都是不相等的, 还有其它的差异可能也会考虑到. 举个例子: a ≠ ba ≠ áa ≠ A.
  • +
+ +

The default is "variant" for usage "sort"; it's locale dependent for usage "search".

+
+
ignorePunctuation
+
指定是否忽略标点. 可能的值是 true and false; 默认为 false.
+
numeric
+
是否指定使用数字排序, 像这样 "1" < "2" < "10". 可能的值是 true 和 false; 默认为 false. 这个选项能被通过options 属性设置或通过 Unicode 扩展。假如两个都被设置了, 则 options 优先。 实现不用必须支持这个属性.
+
caseFirst
+
指定大小写有限排序. 可能的值有 "upper""lower", or "false" (use the locale's default); 默认为 "false". 这个选项能被通过options 属性设置或通过 Unicode 扩展。假如两个都被设置了, 则 options 优先。 实现不用必须支持这个属性.
+
+
+
+

返回值

+ +

如果引用字符存在于比较字符之前则为负数; 如果引用字符存在于比较字符之后则为正数; 相等的时候返回 0 .

+
+
page('/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Collator', 'Parameters')}}
+
+ +

描述

+ +

返回一个数字表示是否 引用字符串 在排序中位于 比较字符串 的前面,后面,或者二者相同。

+ + + +

切勿依赖于 -1 或 1 这样特定的返回值。不同浏览器之间(以及不同浏览器版本之间) 返回的正负数的值各有不同,因为W3C规范中只要求返回值是正值和负值,而没有规定具体的值。一些浏览器可能返回-2或2或其他一些负的、正的值。

+ +

示例

+ +

使用 localeCompare()

+ +
// The letter "a" is before "c" yielding a negative value
+'a'.localeCompare('c');
+// -2 or -1 (or some other negative value)
+
+// Alphabetically the word "check" comes after "against" yielding a positive value
+'check'.localeCompare('against');
+// 2 or 1 (or some other positive value)
+
+// "a" and "a" are equivalent yielding a neutral value of zero
+'a'.localeCompare('a');
+// 0
+
+ +

检查浏览器对扩展参数的支持

+ +

locales 和 options 参数还没有被所有浏览器所支持。检查是否被支持, 使用 "i" 参数 (a requirement that illegal language tags are rejected) 判断是否有异常 {{jsxref("RangeError")}}抛出:

+ +
function localeCompareSupportsLocales() {
+  try {
+    'foo'.localeCompare​('bar', 'i');
+  } catch (e) {
+    return e​.name === 'RangeError';
+  }
+  return false;
+}
+
+ +

使用 locales 参数

+ +

在不同的语言下 localeCompare() 所提供的结果是不一致的。 为了能让用户得到正确的比较值, 通过使用 locales 参数来提供要比较的语言 (and possibly some fallback languages) :

+ +
console.log('ä'.localeCompare('z', 'de')); // a negative value: in German, ä sorts with a
+console.log('ä'.localeCompare('z', 'sv')); // a positive value: in Swedish, ä sorts after z
+
+ +

使用 options 参数

+ +

localeCompare() 所提供的结果可以通过 options 参数来制定:

+ +
// in German, ä has a as the base letter
+console.log('ä'.localeCompare('a', 'de', { sensitivity: 'base' })); // 0
+
+// in Swedish, ä and a are separate base letters
+console.log('ä'.localeCompare('a', 'sv', { sensitivity: 'base' })); // a positive value
+
+ +

性能相关

+ +

当比较大量字符串时, 比如比较大量数组时, 最好创建一个{{jsxref("Global_Objects/Collator", "Intl.Collator")}} 对象并使用{{jsxref("Collator.prototype.compare", "compare")}} 属性所提供的函数。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.9', 'String.prototype.localeCompare')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.localecompare', 'String.prototype.localeCompare')}}{{Spec2('ES6')}}
{{SpecName('ES Int 1.0', '#sec-13.1.1', 'String.prototype.localeCompare')}}{{Spec2('ES Int 1.0')}}locale and option parameter definitions.
+ +

浏览器兼容性

+ + + +

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

+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/match/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/match/index.html new file mode 100644 index 0000000000..9922ea3291 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/match/index.html @@ -0,0 +1,215 @@ +--- +title: String.prototype.match() +slug: Web/JavaScript/Reference/Global_Objects/String/match +translation_of: Web/JavaScript/Reference/Global_Objects/String/match +--- +

{{JSRef}}

+ +

 match() 方法检索返回一个字符串匹配正则表达式的结果。

+ + +
{{EmbedInteractiveExample("pages/js/string-match.html", "shorter")}}
+ + + +

语法

+ +
str.match(regexp)
+ +

参数

+ +
+
regexp
+
一个正则表达式对象。如果传入一个非正则表达式对象,则会隐式地使用 new RegExp(obj) 将其转换为一个 {{jsxref("RegExp")}} 。如果你没有给出任何参数并直接使用match() 方法 ,你将会得到一 个包含空字符串的 {{jsxref("Array")}} :[""] 。
+
+ +

返回值

+ + + +

附加属性

+ +

如上所述,匹配的结果包含如下所述的附加特性。

+ + + +
+
一个{{jsxref("Array")}},其内容取决于global(g)标志的存在与否,如果未找到匹配则为{{jsxref("null")}}。
+
+ +

描述

+ +

如果正则表达式不包含 标志,str.match() 将返回与 {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}}. 相同的结果。

+ +

参看:RegExp 方法

+ + + +

示例

+ +

例子:使用 match

+ +

在下例中,使用 match 查找 "Chapter" 紧跟着 1 个或多个数值字符,再紧跟着一个小数点和数值字符 0 次或多次。正则表达式包含 i 标志,因此大小写会被忽略。

+ +
var str = 'For more information, see Chapter 3.4.5.1';
+var re = /see (chapter \d+(\.\d)*)/i;
+var found = str.match(re);
+
+console.log(found);
+
+// logs [ 'see Chapter 3.4.5.1',
+//        'Chapter 3.4.5.1',
+//        '.1',
+//        index: 22,
+//        input: 'For more information, see Chapter 3.4.5.1' ]
+
+// 'see Chapter 3.4.5.1' 是整个匹配。
+// 'Chapter 3.4.5.1' 被'(chapter \d+(\.\d)*)'捕获。
+// '.1' 是被'(\.\d)'捕获的最后一个值。
+// 'index' 属性(22) 是整个匹配从零开始的索引。
+// 'input' 属性是被解析的原始字符串。
+ +

例子:match 使用全局(global)和忽略大小写(ignore case)标志

+ +

下例展示了 match 使用 global 和 ignore case 标志。A-E、a-e 的所有字母将会作为一个数组的元素返回。

+ +
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
+var regexp = /[A-E]/gi;
+var matches_array = str.match(regexp);
+
+console.log(matches_array);
+// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']
+ +

使用match(),不传参数

+ +
var str = "Nothing will come of nothing.";
+
+str.match();   // returns [""]
+ +

一个非正则表达式对象作为参数

+ +

当参数是一个字符串或一个数字,它会使用new RegExp(obj)来隐式转换成一个 {{jsxref("RegExp")}}。如果它是一个有正号的正数,RegExp() 方法将忽略正号。

+ +
var str1 = "NaN means not a number. Infinity contains -Infinity and +Infinity in JavaScript.",
+    str2 = "My grandfather is 65 years old and My grandmother is 63 years old.",
+    str3 = "The contract was declared null and void.";
+str1.match("number");   // "number" 是字符串。返回["number"]
+str1.match(NaN);        // NaN的类型是number。返回["NaN"]
+str1.match(Infinity);   // Infinity的类型是number。返回["Infinity"]
+str1.match(+Infinity);  // 返回["Infinity"]
+str1.match(-Infinity);  // 返回["-Infinity"]
+str2.match(65);         // 返回["65"]
+str2.match(+65);        // 有正号的number。返回["65"]
+str3.match(null);       // 返回["null"]
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.10', 'String.prototype.match')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.match', 'String.prototype.match')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.match', 'String.prototype.match')}}{{Spec2('ESDraft')}}
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Firefox 特殊注意

+ + + +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/matchall/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/matchall/index.html new file mode 100644 index 0000000000..5fd54c46aa --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/matchall/index.html @@ -0,0 +1,135 @@ +--- +title: String.prototype.matchAll() +slug: Web/JavaScript/Reference/Global_Objects/String/matchAll +tags: + - JavaScript + - Method + - Prototype + - Reference + - Regular Expressions + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/matchAll +--- +
{{JSRef}}
+ +

matchAll() 方法返回一个包含所有匹配正则表达式的结果及分组捕获组的迭代器。

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

语法

+ +
str.matchAll(regexp)
+ +

参数

+ +
+
regexp
+
+ +

    正则表达式对象。如果所传参数不是一个正则表达式对象,则会隐式地使用 new RegExp(obj) 将其转换为一个 RegExp 。

+ +

    RegExp必须是设置了全局模式g的形式,否则会抛出异常TypeError

+ +

返回值

+ +

一个迭代器(不可重用,结果耗尽需要再次调用方法,获取一个新的迭代器)。

+ +

例子

+ +

Regexp.exec() 和 matchAll()

+ +

matchAll 出现之前,通过在循环中调用 regexp.exec() 来获取所有匹配项信息(regexp 需使用 /g 标志):

+ +
const regexp = RegExp('foo[a-z]*','g');
+const str = 'table football, foosball';
+let match;
+
+while ((match = regexp.exec(str)) !== null) {
+  console.log(`Found ${match[0]} start=${match.index} end=${regexp.lastIndex}.`);
+  // expected output: "Found football start=6 end=14."
+  // expected output: "Found foosball start=16 end=24."
+}
+ +

如果使用 matchAll ,就可以不必使用 while 循环加 exec 方式(且正则表达式需使用 /g 标志)。使用 matchAll 会得到一个迭代器的返回值,配合 for...of, array spread, 或者 {{jsxref("Array.from()")}} 可以更方便实现功能:

+ +
const regexp = RegExp('foo[a-z]*','g');
+const str = 'table football, foosball';
+const matches = str.matchAll(regexp);
+
+for (const match of matches) {
+  console.log(`Found ${match[0]} start=${match.index} end=${match.index + match[0].length}.`);
+}
+// expected output: "Found football start=6 end=14."
+// expected output: "Found foosball start=16 end=24."
+
+// matches iterator is exhausted after the for..of iteration
+// Call matchAll again to create a new iterator
+Array.from(str.matchAll(regexp), m => m[0]);
+// Array [ "football", "foosball" ]
+ +

如果没有 /g 标志,matchAll 会抛出异常。

+ +
const regexp = RegExp('[a-c]','');
+const str = 'abc';
+Array.from(str.matchAll(regexp), m => m[0]);
+// TypeError: String.prototype.matchAll called with a non-global RegExp argument
+ +

matchAll 内部做了一个 regexp 的复制,所以不像 regexp.execlastIndex 在字符串扫描时不会改变。

+ +
const regexp = RegExp('[a-c]','g');
+regexp.lastIndex = 1;
+const str = 'abc';
+Array.from(str.matchAll(regexp), m => `${regexp.lastIndex} ${m[0]}`);
+// Array [ "1 b", "1 c" ]
+
+ +

捕获组的更佳途径

+ +

matchAll 的另外一个亮点是更好地获取捕获组。因为当使用 match() 和 /g 标志方式获取匹配信息时,捕获组会被忽略:

+ +
var regexp = /t(e)(st(\d?))/g;
+var str = 'test1test2';
+
+str.match(regexp);
+// Array ['test1', 'test2']
+ +

使用 matchAll 可以通过如下方式获取分组捕获:

+ +
let array = [...str.matchAll(regexp)];
+
+array[0];
+// ['test1', 'e', 'st1', '1', index: 0, input: 'test1test2', length: 4]
+array[1];
+// ['test2', 'e', 'st2', '2', index: 5, input: 'test1test2', length: 4]
+
+ +

规范

+ + + + + + + + + + + + +
SpecificationStatus
{{SpecName('ESDraft', '#sec-string.prototype.matchall', 'String.prototype.matchAll')}}{{Spec2('ESDraft')}}
+ +

浏览器兼容性

+ + + +

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

+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/normalize/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/normalize/index.html new file mode 100644 index 0000000000..3a054a9172 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/normalize/index.html @@ -0,0 +1,231 @@ +--- +title: String.prototype.normalize() +slug: Web/JavaScript/Reference/Global_Objects/String/normalize +tags: + - ECMAScript 2015 + - JavaScript + - Method + - String + - Unicode + - 参考 + - 字符串 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/String/normalize +--- +

{{JSRef}}

+ +

normalize() 方法会按照指定的一种 Unicode 正规形式将当前字符串正规化。(如果该值不是字符串,则首先将其转换为一个字符串)。

+ +
{{EmbedInteractiveExample("pages/js/string-normalize.html", "taller")}}
+ + + +

语法

+ +
str.normalize([form])
+ +

参数

+ +
+
form {{optional_inline}}
+
+

四种 Unicode 正规形式(Unicode Normalization Form)"NFC""NFD""NFKC",或 "NFKD" 其中的一个, 默认值为 "NFC"

+ +

这四个值的含义分别如下:

+ +
+
"NFC"
+
Canonical Decomposition, followed by Canonical Composition.
+
"NFD"
+
Canonical Decomposition.
+
"NFKC"
+
Compatibility Decomposition, followed by Canonical Composition.
+
"NFKD"
+
Compatibility Decomposition.
+
+
+
+ +

返回值

+ +

含有给定字符串的 Unicode 规范化形式的字符串。

+ +

可能出现的异常

+ +
+
{{jsxref("RangeError")}}
+
如果给 form 传入了上述四个字符串以外的参数,则会抛出 RangeError 异常。
+
+ +

描述

+ +

Unicode assigns a unique numerical value, called a code point, to each character. For example, the code point for "A" is given as U+0041. However, sometimes more than one code point, or sequence of code points, can represent the same abstract character — the character "ñ" for example can be represented by either of:

+ + + +
let string1 = '\u00F1';
+let string2 = '\u006E\u0303';
+
+console.log(string1);  //  ñ
+console.log(string2);  //  ñ
+
+ +

However, since the code points are different, string comparison will not treat them as equal. And since the number of code points in each version is different, they even have different lengths.

+ +
let string1 = '\u00F1';            // ñ
+let string2 = '\u006E\u0303';      // ñ
+
+console.log(string1 === string2); // false
+console.log(string1.length);      // 1
+console.log(string2.length);      // 2
+
+ +

The normalize() method helps solve this problem by converting a string into a normalized form common for all sequences of code points that represent the same characters. There are two main normalization forms, one based on canonical equivalence and the other based on compatibility.

+ +

Canonical equivalence normalization

+ +

In Unicode, two sequences of code points have canonical equivalence if they represent the same abstract characters, and should always have the same visual appearance and behavior (for example, they should always be sorted in the same way).

+ +

You can use normalize() using the "NFD" or "NFC" arguments to produce a form of the string that will be the same for all canonically equivalent strings. In the example below we normalize two representations of the character "ñ":

+ +
let string1 = '\u00F1';           // ñ
+let string2 = '\u006E\u0303';     // ñ
+
+string1 = string1.normalize('NFD');
+string2 = string2.normalize('NFD');
+
+console.log(string1 === string2); // true
+console.log(string1.length);      // 2
+console.log(string2.length);      // 2
+
+ +

Composed and decomposed forms

+ +

Note that the length of the normalized form under "NFD" is 2. That's because "NFD" gives you the decomposed version of the canonical form, in which single code points are split into multiple combining ones. The decomposed canonical form for "ñ" is "\u006E\u0303".

+ +

You can specify "NFC" to get the composed canonical form, in which multiple code points are replaced with single code points where possible. The composed canonical form for "ñ" is "\u00F1":

+ +
let string1 = '\u00F1';                           // ñ
+let string2 = '\u006E\u0303';                     // ñ
+
+string1 = string1.normalize('NFC');
+string2 = string2.normalize('NFC');
+
+console.log(string1 === string2);                 // true
+console.log(string1.length);                      // 1
+console.log(string2.length);                      // 1
+console.log(string2.codePointAt(0).toString(16)); // f1
+ +

Compatibility normalization

+ +

In Unicode, two sequences of code points are compatible if they represent the same abstract characters, and should be treated alike in some — but not necessarily all — applications.

+ +

All canonically equivalent sequences are also compatible, but not vice versa.

+ +

For example, the code point U+FB00 represents the ligature "ff". It is compatible with two consecutive U+0066 code points ("ff").

+ +

In some respects (such as sorting) they should be treated as equivalent—and in some (such as visual appearance) they should not, so they are not canonically equivalent.

+ +

You can use normalize() using the "NFKD" or "NFKC" arguments to produce a form of the string that will be the same for all compatible strings:

+ +
let string1 = '\uFB00';
+let string2 = '\u0066\u0066';
+
+console.log(string1);             // ff
+console.log(string2);             // ff
+console.log(string1 === string2); // false
+console.log(string1.length);      // 1
+console.log(string2.length);      // 2
+
+string1 = string1.normalize('NFKD');
+string2 = string2.normalize('NFKD');
+
+console.log(string1);             // ff <- visual appearance changed
+console.log(string2);             // ff
+console.log(string1 === string2); // true
+console.log(string1.length);      // 2
+console.log(string2.length);      // 2
+
+ +

When applying compatibility normalization it's important to consider what you intend to do with the strings, since the normalized form may not be appropriate for all applications. In the example above the normalization is appropriate for search, because it enables a user to find the string by searching for "f". But it may not be appropriate for display, because the visual representation is different.

+ +

As with canonical normalization, you can ask for decomposed or composed compatible forms by passing "NFKD" or "NFKC", respectively.

+ +

示例

+ +

使用 normalize()

+ +
// Initial string
+
+// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE
+// U+0323: COMBINING DOT BELOW
+var str = "\u1E9B\u0323";
+
+
+// Canonically-composed form (NFC)
+
+// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE
+// U+0323: COMBINING DOT BELOW
+str.normalize("NFC"); // "\u1E9B\u0323"
+str.normalize(); // same as above
+
+
+// Canonically-decomposed form (NFD)
+
+// U+017F: LATIN SMALL LETTER LONG S
+// U+0323: COMBINING DOT BELOW
+// U+0307: COMBINING DOT ABOVE
+str.normalize("NFD"); // "\u017F\u0323\u0307"
+
+
+// Compatibly-composed (NFKC)
+
+// U+1E69: LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE
+str.normalize("NFKC"); // "\u1E69"
+
+
+// Compatibly-decomposed (NFKD)
+
+// U+0073: LATIN SMALL LETTER S
+// U+0323: COMBINING DOT BELOW
+// U+0307: COMBINING DOT ABOVE
+str.normalize("NFKD"); // "\u0073\u0323\u0307"
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('ESDraft', '#sec-string.prototype.normalize', 'String.prototype.normalize')}}{{Spec2('ESDraft')}}
{{SpecName('ES2015', '#sec-string.prototype.normalize', 'String.prototype.normalize')}}{{Spec2('ES2015')}}Initial definition.
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/padend/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/padend/index.html new file mode 100644 index 0000000000..4b06856b03 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/padend/index.html @@ -0,0 +1,100 @@ +--- +title: String.prototype.padEnd() +slug: Web/JavaScript/Reference/Global_Objects/String/padEnd +tags: + - JavaScript + - Method + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/padEnd +--- +
{{JSRef}}
+ +

padEnd()  方法会用一个字符串填充当前字符串(如果需要的话则重复填充),返回填充后达到指定长度的字符串。从当前字符串的末尾(右侧)开始填充。

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

语法

+ +
str.padEnd(targetLength [, padString])
+ +

参数

+ +
+
targetLength
+
当前字符串需要填充到的目标长度。如果这个数值小于当前字符串的长度,则返回当前字符串本身。
+
padString {{optional_inline}}
+
填充字符串。如果字符串太长,使填充后的字符串长度超过了目标长度,则只保留最左侧的部分,其他部分会被截断。此参数的缺省值为 " "(U+0020)。
+
+ +

返回值

+ +

在原字符串末尾填充指定的填充字符串直到目标长度所形成的新字符串。

+ +

示例

+ +
'abc'.padEnd(10);          // "abc       "
+'abc'.padEnd(10, "foo");   // "abcfoofoof"
+'abc'.padEnd(6, "123456"); // "abc123"
+'abc'.padEnd(1);           // "abc"
+
+ +

Polyfill

+ +

如果原生环境不支持该方法,在其他代码之前先运行下面的代码,将创建 String.prototype.padEnd() 方法。

+ +
// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
+// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
+if (!String.prototype.padEnd) {
+    String.prototype.padEnd = function padEnd(targetLength,padString) {
+        targetLength = targetLength>>0; //floor if number or convert non-number to 0;
+        padString = String((typeof padString !== 'undefined' ? padString: ''));
+        if (this.length > targetLength) {
+            return String(this);
+        }
+        else {
+            targetLength = targetLength-this.length;
+            if (targetLength > padString.length) {
+                padString += padString.repeat(targetLength/padString.length); //append to original to ensure we are longer than needed
+            }
+            return String(this) + padString.slice(0,targetLength);
+        }
+    };
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-string.prototype.padend', 'String.prototype.padEnd')}}{{Spec2('ESDraft')}}在 ECMAScript 2017 中首次被定义。
{{SpecName('ES8', '#sec-string.prototype.padend', 'String.prototype.padEnd')}}{{Spec2('ES8')}}
+ +

浏览器兼容性

+ + + +

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

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/padstart/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/padstart/index.html new file mode 100644 index 0000000000..24431715d0 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/padstart/index.html @@ -0,0 +1,102 @@ +--- +title: String.prototype.padStart() +slug: Web/JavaScript/Reference/Global_Objects/String/padStart +tags: + - ECMAScript 2017 + - JavaScript + - Method + - Reference + - String + - String.padStart() +translation_of: Web/JavaScript/Reference/Global_Objects/String/padStart +--- +
{{JSRef}}
+ +

padStart() 方法用另一个字符串填充当前字符串(如果需要的话,会重复多次),以便产生的字符串达到给定的长度。从当前字符串的左侧开始填充。

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

语法

+ +
str.padStart(targetLength [, padString])
+ +

参数

+ +
+
targetLength
+
当前字符串需要填充到的目标长度。如果这个数值小于当前字符串的长度,则返回当前字符串本身。
+
padString {{optional_inline}}
+
填充字符串。如果字符串太长,使填充后的字符串长度超过了目标长度,则只保留最左侧的部分,其他部分会被截断。此参数的默认值为 " "(U+0020)。
+
+ +

返回值

+ +

在原字符串开头填充指定的填充字符串直到目标长度所形成的新字符串。

+ +

示例

+ +
'abc'.padStart(10);         // "       abc"
+'abc'.padStart(10, "foo");  // "foofoofabc"
+'abc'.padStart(6,"123465"); // "123abc"
+'abc'.padStart(8, "0");     // "00000abc"
+'abc'.padStart(1);          // "abc"
+ +

Polyfill

+ +

如果原生环境不支持该方法,在其他代码之前先运行下面的代码,将创建 String.prototype.padStart() 方法。

+ +
// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
+// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
+if (!String.prototype.padStart) {
+    String.prototype.padStart = function padStart(targetLength,padString) {
+        targetLength = targetLength>>0; //floor if number or convert non-number to 0;
+        padString = String((typeof padString !== 'undefined' ? padString : ' '));
+        if (this.length > targetLength) {
+            return String(this);
+        }
+        else {
+            targetLength = targetLength-this.length;
+            if (targetLength > padString.length) {
+                padString += padString.repeat(targetLength/padString.length); //append to original to ensure we are longer than needed
+            }
+            return padString.slice(0,targetLength) + String(this);
+        }
+    };
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('ESDraft', '#sec-string.prototype.padstart', 'String.prototype.padStart')}}{{Spec2('ESDraft')}}在 ECMAScript 2017 中首次被定义。
{{SpecName('ES8', '#sec-string.prototype.padstart', 'String.prototype.padStart')}}{{Spec2('ES8')}}
+ +

浏览器兼容性

+ + + +

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

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/prototype/index.html new file mode 100644 index 0000000000..88b792052b --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/prototype/index.html @@ -0,0 +1,186 @@ +--- +title: String.prototype +slug: Web/JavaScript/Reference/Global_Objects/String/prototype +tags: + - JavaScript + - 原型 + - 参考 + - 字符串 + - 属性 +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +
{{JSRef}}
+ +

 String.prototype 属性表示 {{jsxref("String")}}原型对象。

+ +
{{js_property_attributes(0,0,0)}}
+ +

描述

+ +

所有 {{jsxref("String")}} 的实例都继承自 String.prototype. 任何String.prototype上的改变都会影响到所有的 {{jsxref("String")}} 实例。

+ +

属性

+ +
+
String.prototype.constructor
+
用于创造对象的原型对象的特定的函数。
+
{{jsxref("String.prototype.length")}}
+
返回了字符串的长度。
+
N
+
用于访问第N个位置的字符,其中N是小于 {{jsxref("String.length", "length")}} 和 0之间的正整数。这些属性都是“只读”性质,不能编辑。
+
+ +

方法

+ +

跟HTML无关的方法

+ +
+
{{jsxref("String.prototype.charAt()")}}
+
返回特定位置的字符。
+
{{jsxref("String.prototype.charCodeAt()")}}
+
返回表示给定索引的字符的Unicode的值。
+
{{jsxref("String.prototype.codePointAt()")}}
+
返回使用UTF-16编码的给定位置的值的非负整数。
+
{{jsxref("String.prototype.concat()")}}
+
连接两个字符串文本,并返回一个新的字符串。
+
{{jsxref("String.prototype.includes()")}}
+
判断一个字符串里是否包含其他字符串。
+
{{jsxref("String.prototype.endsWith()")}}
+
判断一个字符串的是否以给定字符串结尾,结果返回布尔值。
+
{{jsxref("String.prototype.indexOf()")}}
+
从字符串对象中返回首个被发现的给定值的索引值,如果没有找到则返回-1。
+
{{jsxref("String.prototype.lastIndexOf()")}}
+
从字符串对象中返回最后一个被发现的给定值的索引值,如果没有找到则返回-1。
+
{{jsxref("String.prototype.localeCompare()")}}
+
返回一个数字表示是否引用字符串在排序中位于比较字符串的前面,后面,或者二者相同。
+
{{jsxref("String.prototype.match()")}}
+
使用正则表达式与字符串相比较。
+
{{jsxref("String.prototype.normalize()")}}
+
返回调用字符串值的Unicode标准化形式。
+
{{jsxref("String.prototype.padEnd()")}}
+
在当前字符串尾部填充指定的字符串, 直到达到指定的长度。 返回一个新的字符串。
+
{{jsxref("String.prototype.padStart()")}}
+
+

在当前字符串头部填充指定的字符串, 直到达到指定的长度。 返回一个新的字符串。

+
+
{{jsxref("String.prototype.quote()")}} {{ obsolete_inline }}
+
设置嵌入引用的引号类型。
+
{{jsxref("String.prototype.repeat()")}}
+
返回指定重复次数的由元素组成的字符串对象。
+
{{jsxref("String.prototype.replace()")}}
+
被用来在正则表达式和字符串直接比较,然后用新的子串来替换被匹配的子串。
+
{{jsxref("String.prototype.search()")}}
+
对正则表达式和指定字符串进行匹配搜索,返回第一个出现的匹配项的下标。
+
{{jsxref("String.prototype.slice()")}}
+
摘取一个字符串区域,返回一个新的字符串。
+
{{jsxref("String.prototype.split()")}}
+
通过分离字符串成字串,将字符串对象分割成字符串数组。
+
{{jsxref("String.prototype.startsWith()")}}
+
判断字符串的起始位置是否匹配其他字符串中的字符。
+
{{jsxref("String.prototype.substr()")}}
+
通过指定字符数返回在指定位置开始的字符串中的字符。
+
{{jsxref("String.prototype.substring()")}}
+
返回在字符串中指定两个下标之间的字符。
+
{{jsxref("String.prototype.toLocaleLowerCase()")}}
+
根据当前区域设置,将符串中的字符转换成小写。对于大多数语言来说,{{jsxref("String.toLowerCase", "toLowerCase")}}的返回值是一致的。
+
{{jsxref("String.prototype.toLocaleUpperCase()")}}
+
根据当前区域设置,将字符串中的字符转换成大写,对于大多数语言来说,{{jsxref("String.toUpperCase", "toUpperCase")}}的返回值是一致的。
+
{{jsxref("String.prototype.toLowerCase()")}}
+
将字符串转换成小写并返回。
+
{{jsxref("String.prototype.toSource()")}} {{ Non-standard_inline() }}
+
返回一个对象文字代表着特定的对象。你可以使用这个返回值来创建新的对象。重写 {{jsxref("Object.prototype.toSource")}} 方法。
+
{{jsxref("String.prototype.toString()")}}
+
返回用字符串表示的特定对象。重写 {{jsxref("Object.prototype.toString")}} 方法。
+
{{jsxref("String.prototype.toUpperCase()")}}
+
将字符串转换成大写并返回。
+
{{jsxref("String.prototype.trim()")}}
+
从字符串的开始和结尾去除空格。参照部分 ECMAScript 5 标准。
+
{{jsxref("String.prototype.trimStart()")}}
+
{{jsxref("String.prototype.trimLeft()")}} {{ Non-standard_inline() }}
+
从字符串的左侧去除空格。
+
{{jsxref("String.prototype.trimEnd()")}}
+
{{jsxref("String.prototype.trimRight()")}} {{ Non-standard_inline() }}
+
从字符串的右侧去除空格。
+
{{jsxref("String.prototype.valueOf()")}}
+
返回特定对象的原始值。重写 {{jsxref("Object.prototype.valueOf")}} 方法。
+
{{jsxref("String.prototype.@@iterator()", "String.prototype[@@iterator]()")}}
+
返回一个新的迭代器对象,该对象遍历字符串值的索引位置,将每个索引值作为字符串值返回。
+
+ +

HTML wrapper methods

+ +

下面的方法被限制使用,因为只对可用的HTML标签和属性提供部分支持。

+ +
+
{{jsxref("String.prototype.anchor()")}}
+
<a name="name"> (hypertext target)
+
{{jsxref("String.prototype.big()")}} {{deprecated_inline}}
+
{{HTMLElement("big")}}
+
{{jsxref("String.prototype.blink()")}} {{deprecated_inline}}
+
{{HTMLElement("blink")}}
+
{{jsxref("String.prototype.bold()")}} {{deprecated_inline}}
+
{{HTMLElement("b")}}
+
{{jsxref("String.prototype.fixed()")}} {{deprecated_inline}}
+
{{HTMLElement("tt")}}
+
{{jsxref("String.prototype.fontcolor()")}} {{deprecated_inline}}
+
<font color="color">
+
{{jsxref("String.prototype.fontsize()")}} {{deprecated_inline}}
+
<font size="size">
+
{{jsxref("String.prototype.italics()")}} {{deprecated_inline}}
+
{{HTMLElement("i")}}
+
{{jsxref("String.prototype.link()")}}
+
<a href="url"> (link to URL)
+
{{jsxref("String.prototype.small()")}} {{deprecated_inline}}
+
{{HTMLElement("small")}}
+
{{jsxref("String.prototype.strike()")}} {{deprecated_inline}}
+
{{HTMLElement("strike")}}
+
{{jsxref("String.prototype.sub()")}} {{deprecated_inline}}
+
{{HTMLElement("sub")}}
+
{{jsxref("String.prototype.sup()")}} {{deprecated_inline}}
+
{{HTMLElement("sup")}}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
ECMAScript 1st Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.5.3.1', 'String.prototype')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype', 'String.prototype')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype', 'String.prototype')}}{{Spec2('ESDraft')}}
+ +

浏览器兼容性

+ + + +

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

+ +

更多

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/quote/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/quote/index.html new file mode 100644 index 0000000000..3d8d197f46 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/quote/index.html @@ -0,0 +1,116 @@ +--- +title: String.prototype.quote() +slug: Web/JavaScript/Reference/Global_Objects/String/quote +tags: + - JavaScript + - Method + - Non-standard + - Obsolete + - Prototype + - String +translation_of: Archive/Web/JavaScript/String.quote +--- +
{{obsolete_header("37")}}
+ +
{{JSRef("Global_Objects", "String")}}{{Non-standard_header}}
+ +

概述

+ +

将字符串中包含的特殊字符进行转义(反斜杠),然后在字符串两边各加上一个双引号(")并返回,并不修改原字符串.

+ +

语法

+ +
str.quote()
+ +

示例

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
strstr.quote()eval(str.quote())
Hello world!"Hello world!"Hello world!
Hello
+         world!
"Hello\n\tworld!"Hello
+         world!
" \ — '"\" \\ \u2014 '"" \ — '
+ +

规范

+ +

不在任何规范中。实现于 JavaScript 1.3.

+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/raw/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/raw/index.html new file mode 100644 index 0000000000..89c4d568d5 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/raw/index.html @@ -0,0 +1,113 @@ +--- +title: String.raw() +slug: Web/JavaScript/Reference/Global_Objects/String/raw +tags: + - JavaScript + - Method + - Reference + - String + - 参考 + - 字符串 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/String/raw +--- +
{{JSRef()}}
+ +

String.raw() 是一个模板字符串的标签函数,它的作用类似于 Python 中的字符串前缀 r 和 C# 中的字符串前缀 @(还是有点区别的,详见隔壁 Chromium 那边的这个 issue),是用来获取一个模板字符串的原始字符串的,比如说,占位符(例如 ${foo})会被处理为它所代表的其他字符串,而转义字符(例如 \n)不会。

+ +

语法

+ +
String.raw(callSite, ...substitutions)
+
+String.raw`templateString`
+
+ +

参数

+ +
+
callSite
+
一个模板字符串的“调用点对象”。类似{ raw: ['foo', 'bar', 'baz'] }
+
...substitutions
+
任意个可选的参数,表示任意个内插表达式对应的值。
+
templateString
+
模板字符串,可包含占位符(${...})。
+
+ +

返回值

+ +

给定模板字符串的原始字符串。

+ +

异常

+ +
+
{{jsxref("TypeError")}}
+
如果第一个参数没有传入一个格式正确的对象,则会抛出 TypeError 异常。
+
+ +

描述

+ +

在大多数情况下, String.raw()是用来处理模版字符串的. 不要被上面复杂的参数要求吓到,因为像所有的 tag functions一样,你通常不需要把它看成一个普通函数,你只需要把它放在模板字符串前面就可以了,而不是在它后面加个括号和一堆参数来调用它,引擎会替你去调用它。

+ +

String.raw() 是唯一一个内置的模板字符串标签函数,因为它太常用了。不过它并没有什么特殊能力,你自己也可以实现一个和它功能一模一样的标签函数。

+ +

示例

+ +

使用 String.raw()

+ +
String.raw`Hi\n${2+3}!`;
+// 'Hi\n5!',Hi 后面的字符不是换行符,\ 和 n 是两个不同的字符
+
+String.raw `Hi\u000A!`;
+// "Hi\u000A!",同上,这里得到的会是 \、u、0、0、0、A 6个字符,
+// 任何类型的转义形式都会失效,保留原样输出,不信你试试.length
+
+let name = "Bob";
+String.raw `Hi\n${name}!`;
+// "Hi\nBob!",内插表达式还可以正常运行
+
+
+// 正常情况下,你也许不需要将 String.raw() 当作函数调用。
+// 但是为了模拟 `t${0}e${1}s${2}t` 你可以这样做:
+String.raw({ raw: 'test' }, 0, 1, 2); // 't0e1s2t'
+// 注意这个测试, 传入一个 string, 和一个类似数组的对象
+// 下面这个函数和 `foo${2 + 3}bar${'Java' + 'Script'}baz` 是相等的.
+String.raw({
+  raw: ['foo', 'bar', 'baz']
+}, 2 + 3, 'Java' + 'Script'); // 'foo5barJavaScriptbaz'
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('ES2015', '#sec-string.raw', 'String.raw')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-string.raw', 'String.raw')}}{{Spec2('ESDraft')}}
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/repeat/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/repeat/index.html new file mode 100644 index 0000000000..ce35065f1a --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/repeat/index.html @@ -0,0 +1,124 @@ +--- +title: String.prototype.repeat() +slug: Web/JavaScript/Reference/Global_Objects/String/repeat +tags: + - ECMAScript 2015 + - ES 6 + - JavaScript + - Method + - Prototype + - Reference + - String + - polyfill + - repeat() + - 填充 +translation_of: Web/JavaScript/Reference/Global_Objects/String/repeat +--- +

{{JSRef}}

+ +

repeat() 构造并返回一个新字符串,该字符串包含被连接在一起的指定数量的字符串的副本。

+ +

语法

+ +
str.repeat(count)
+ +

参数

+ +
+
count
+
介于 0 和 {{jsxref("Global_Objects/Number/POSITIVE_INFINITY", "+Infinity")}} 之间的整数。表示在新构造的字符串中重复了多少遍原字符串。
+
+ +

返回值

+ +

 包含指定字符串的指定数量副本的新字符串。

+ +

Exceptions

+ + + +

兼容补丁(Polyfill)

+ +

此方法已添加到 ECMAScript 2015 规范中,并且可能尚未在所有 JavaScript 实现中可用。然而,你可以使用以下代码段对 String.prototype.repeat() 进行填充:

+ +
if (!String.prototype.repeat) {
+  String.prototype.repeat = function(count) {
+    'use strict';
+    if (this == null) {
+      throw new TypeError('can\'t convert ' + this + ' to object');
+    }
+    var str = '' + this;
+    count = +count;
+    if (count != count) {
+      count = 0;
+    }
+    if (count < 0) {
+      throw new RangeError('repeat count must be non-negative');
+    }
+    if (count == Infinity) {
+      throw new RangeError('repeat count must be less than infinity');
+    }
+    count = Math.floor(count);
+    if (str.length == 0 || count == 0) {
+      return '';
+    }
+    // 确保 count 是一个 31 位的整数。这样我们就可以使用如下优化的算法。
+    // 当前(2014年8月),绝大多数浏览器都不能支持 1 << 28 长的字符串,所以:
+    if (str.length * count >= 1 << 28) {
+      throw new RangeError('repeat count must not overflow maximum string size');
+    }
+    var rpt = '';
+    for (;;) {
+      if ((count & 1) == 1) {
+        rpt += str;
+      }
+      count >>>= 1;
+      if (count == 0) {
+        break;
+      }
+      str += str;
+    }
+    return rpt;
+  }
+}
+ + +

示例

+ +
"abc".repeat(-1)     // RangeError: repeat count must be positive and less than inifinity
+"abc".repeat(0)      // ""
+"abc".repeat(1)      // "abc"
+"abc".repeat(2)      // "abcabc"
+"abc".repeat(3.5)    // "abcabcabc" 参数count将会被自动转换成整数.
+"abc".repeat(1/0)    // RangeError: repeat count must be positive and less than inifinity
+
+({toString : () => "abc", repeat : String.prototype.repeat}).repeat(2)
+//"abcabc",repeat是一个通用方法,也就是它的调用者可以不是一个字符串对象.
+ +

规范

+ + + + + + + + + + + + +
规范
{{SpecName('ESDraft', '#sec-string.prototype.repeat', 'String.prototype.repeat')}}
+ +

浏览器兼容性

+ +

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

+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/replace/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/replace/index.html new file mode 100644 index 0000000000..c4d8f758cb --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/replace/index.html @@ -0,0 +1,317 @@ +--- +title: String.prototype.replace() +slug: Web/JavaScript/Reference/Global_Objects/String/replace +tags: + - JavaScript + - Method + - Prototype + - Regular + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/replace +--- +
{{JSRef}}
+ +

replace() 方法返回一个由替换值(replacement)替换部分或所有的模式(pattern)匹配项后的新字符串。模式可以是一个字符串或者一个正则表达式,替换值可以是一个字符串或者一个每次匹配都要调用的回调函数。如果pattern是字符串,则仅替换第一个匹配项。

+ +

原字符串不会改变。

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

语法

+ +
str.replace(regexp|substr, newSubStr|function)
+ +

参数

+ +
+
regexp (pattern)
+
一个{{jsxref("RegExp")}} 对象或者其字面量。该正则所匹配的内容会被第二个参数的返回值替换掉。
+
+ +
+
substr (pattern)
+
一个将被 newSubStr 替换的 {{jsxref("String","字符串")}}。其被视为一整个字符串,而不是一个正则表达式。仅第一个匹配项会被替换。
+
+ +
+
newSubStr (replacement)
+
用于替换掉第一个参数在原字符串中的匹配部分的{{jsxref("String", "字符串")}}。该字符串中可以内插一些特殊的变量名。参考下面的使用字符串作为参数
+
+ +
+
function (replacement)
+
一个用来创建新子字符串的函数,该函数的返回值将替换掉第一个参数匹配到的结果。参考下面的指定一个函数作为参数
+
+ +

返回值

+ +

一个部分或全部匹配由替代模式所取代的新的字符串。

+ +

描述

+ +

该方法并不改变调用它的字符串本身,而只是返回一个新的替换后的字符串。

+ +

在进行全局的搜索替换时,正则表达式需包含 g 标志。

+ +

使用字符串作为参数

+ +

替换字符串可以插入下面的特殊变量名:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
变量名代表的值
$$插入一个 "$"。
$&插入匹配的子串。
$`插入当前匹配的子串左边的内容。
$'插入当前匹配的子串右边的内容。
$n +

假如第一个参数是 {{jsxref("RegExp")}}对象,并且 n 是个小于100的非负整数,那么插入第 n 个括号匹配的字符串。提示:索引是从1开始。如果不存在第 n个分组,那么将会把匹配到到内容替换为字面量。比如不存在第3个分组,就会用“$3”替换匹配到的内容。

+
$<Name> 这里Name 是一个分组名称。如果在正则表达式中并不存在分组(或者没有匹配),这个变量将被处理为空字符串。只有在支持命名分组捕获的浏览器中才能使用。
+ +

指定一个函数作为参数

+ +

你可以指定一个函数作为第二个参数。在这种情况下,当匹配执行后,该函数就会执行。 函数的返回值作为替换字符串。 (注意:上面提到的特殊替换参数在这里不能被使用。) 另外要注意的是,如果第一个参数是正则表达式,并且其为全局匹配模式,那么这个方法将被多次调用,每次匹配都会被调用。

+ +

下面是该函数的参数:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
变量名代表的值
match匹配的子串。(对应于上述的$&。)
p1,p2, ... +

假如replace()方法的第一个参数是一个{{jsxref("RegExp")}} 对象,则代表第n个括号匹配的字符串。(对应于上述的$1,$2等。)例如,如果是用 /(\a+)(\b+)/ 这个来匹配,p1 就是匹配的 \a+p2 就是匹配的 \b+

+
offset +

匹配到的子字符串在原字符串中的偏移量。(比如,如果原字符串是 'abcd',匹配到的子字符串是 'bc',那么这个参数将会是 1)

+
string被匹配的原字符串。
NamedCaptureGroup命名捕获组匹配的对象
+ +

(精确的参数个数依赖于 replace() 的第一个参数是否是一个正则表达式({{jsxref("RegExp")}})对象,以及这个正则表达式中指定了多少个括号子串,如果这个正则表达式里使用了命名捕获, 还会添加一个命名捕获的对象)

+ +

下面的例子将会使 newString 变成 'abc - 12345 - #$*%'

+ +
function replacer(match, p1, p2, p3, offset, string) {
+  // p1 is nondigits, p2 digits, and p3 non-alphanumerics
+  return [p1, p2, p3].join(' - ');
+}
+var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
+console.log(newString);  // abc - 12345 - #$*%
+
+ +

示例

+ +

replace() 中使用正则表达式

+ +

在下面的例子中,replace() 中使用了正则表达式及忽略大小写标示。

+ +
var str = 'Twas the night before Xmas...';
+var newstr = str.replace(/xmas/i, 'Christmas');
+console.log(newstr);  // Twas the night before Christmas...
+
+ +

replace() 中使用 globalignore 选项

+ +

下面的例子中,正则表达式包含有全局替换(g)和忽略大小写(i)的选项,这使得replace方法用'oranges'替换掉了所有出现的"apples".

+ +
var re = /apples/gi;
+var str = "Apples are round, and apples are juicy.";
+var newstr = str.replace(re, "oranges");
+
+// oranges are round, and oranges are juicy.
+console.log(newstr);
+
+ +

交换字符串中的两个单词

+ +

下面的例子演示了如何交换一个字符串中两个单词的位置,这个脚本使用$1 和 $2 代替替换文本。

+ +
var re = /(\w+)\s(\w+)/;
+var str = "John Smith";
+var newstr = str.replace(re, "$2, $1");
+// Smith, John
+console.log(newstr);
+
+ +

使用行内函数来修改匹配到的字符。

+ +

在这个例子中,所有出现的大写字母转换为小写,并且在匹配位置前加一个连字符。重要的是,在返回一个替换了的字符串前,在匹配元素前进行添加操作是必要的。

+ +

在返回前,替换函数允许匹配片段作为参数,并且将它和连字符进行连接作为新的片段。

+ +
function styleHyphenFormat(propertyName) {
+  function upperToHyphenLower(match) {
+    return '-' + match.toLowerCase();
+  }
+  return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
+}
+
+ +

运行 styleHyphenFormat('borderTop')返回 'border-top'。

+ +

因为我们想在最终的替换中进一步转变匹配结果,所以我们必须使用一个函数。这迫使我们在使用{{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}}方法前进行评估。如果我们尝试不用一个函数进行匹配,那么使用{{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} 方法将不会有效。

+ +
var newString = propertyName.replace(/[A-Z]/g, '-' + '$&'.toLowerCase());  // won't work
+
+ +

这是因为 '$&'.toLowerCase() 会先被解析成字符串字面量(这会导致相同的'$&')而不是当作一个模式。

+ +

将华氏温度转换为对等的摄氏温度

+ +

下面的例子演示如何将华氏温度转换为对等的摄氏温度。华氏温度用一个数字加一个"F"来表示,这个函数将返回一个数字加"C"来表示的摄氏温度。例如,如果输入是 212F,这个函数将返回 100C。如果输入的数字是 0F,这个方法将返回 "-17.77777777777778C"。

+ +

正则表达式test检查任何数字是否以 F 结尾。华氏温度通过第二个参数p1进入函数。这个函数基于华氏温度作为字符串传递给f2c函数设置成摄氏温度。然后f2c()返回摄氏温度。这个函数与Perl的 s///e 标志相似。

+ +
function f2c(x)
+{
+  function convert(str, p1, offset, s)
+  {
+    return ((p1-32) * 5/9) + "C";
+  }
+  var s = String(x);
+  var test = /(\d+(?:\.\d*)?)F\b/g;
+  return s.replace(test, convert);
+}
+
+ +

使用行内函数和正则来避免循环

+ +

下例把某种模式的字符串转换为一个对象数组(其元素为对象)。

+ +

输入:
+ 一个由 x,- 和 _ 组成的字符串。

+ +
x-x_
+
+---x---x---x---
+
+-xxx-xx-x-
+
+_x_x___x___x___
+
+ +

输出:

+ +

一个数组对象。'x' 产生一个 'on' 状态,'-'(连接符)产生一个 'off' 状态,而 '_' (下划线)表示 'on' 状态的长度。

+ +
[
+  { on: true, length: 1 },
+  { on: false, length: 1 },
+  { on: true, length: 2 }
+  ...
+]
+ +

代码片段:

+ +
var str = 'x-x_';
+var retArr = [];
+str.replace(/(x_*)|(-)/g, function(match, p1, p2) {
+  if (p1) { retArr.push({ on: true, length: p1.length }); }
+  if (p2) { retArr.push({ on: false, length: 1 }); }
+});
+
+console.log(retArr);
+ +

该代码片段生成了一个数组,包含三个期望格式的对象,避免了使用 for 循环语句。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.11', 'String.prototype.replace')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.replace', 'String.prototype.replace')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.replace', 'String.prototype.replace')}}{{Spec2('ESDraft')}}
+ +

浏览器兼容性

+ + + +

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

+ +

Firefox 备注

+ + + +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/replaceall/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/replaceall/index.html new file mode 100644 index 0000000000..b79277e488 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/replaceall/index.html @@ -0,0 +1,171 @@ +--- +title: String.prototype.replaceAll() +slug: Web/JavaScript/Reference/Global_Objects/String/replaceAll +tags: + - global flag / g + - replace + - replaceAll +translation_of: Web/JavaScript/Reference/Global_Objects/String/replaceAll +--- +
{{JSRef}}
+ +

replaceAll() 方法返回一个新字符串,新字符串所有满足 pattern 的部分都已被replacement 替换。pattern可以是一个字符串或一个 {{jsxref("RegExp")}}, replacement可以是一个字符串或一个在每次匹配被调用的函数。

+ +

原始字符串保持不变。

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

语法

+ +
const newStr = str.replaceAll(regexp|substr, newSubstr|function)
+ +
+

当使用一个 `regex`时,您必须设置全局(“ g”)标志,
+ 否则,它将引发 TypeError:“必须使用全局 RegExp 调用 replaceAll”。

+
+ +

参数

+ +
+
regexp (pattern)
+
A {{jsxref("RegExp")}} object or literal with the global flag. The matches are replaced with newSubstr or the value returned by the specified function. A RegExp without the global ("g") flag will throw a TypeError: "replaceAll must be called with a global RegExp".
+
substr
+
A {{jsxref("String")}} that is to be replaced by newSubstr. It is treated as a literal string and is not interpreted as a regular expression.
+
newSubstr (replacement)
+
The {{jsxref("String")}} that replaces the substring specified by the specified regexp or substr parameter. A number of special replacement patterns are supported; see the "Specifying a string as a parameter" section below.
+
function (replacement)
+
A function to be invoked to create the new substring to be used to replace the matches to the given regexp or substr. The arguments supplied to this function are described in the "Specifying a function as a parameter" section below.
+
+ +

返回值

+ +

A new string, with all matches of a pattern replaced by a replacement.

+ +

描述

+ +

此方法不会更改调用 {{jsxref("String")}} 对象。它只是返回一个新字符串。

+ +

将一个字符串作为一个参数

+ +

The replacement string can include the following special replacement patterns:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PatternInserts
$$Inserts a "$".
$&Inserts the matched substring.
$`Inserts the portion of the string that precedes the matched substring.
$'Inserts the portion of the string that follows the matched substring.
$nWhere n is a positive integer less than 100, inserts the nth parenthesized submatch string, provided the first argument was a {{jsxref("RegExp")}} object. Note that this is 1-indexed.
+ +

将一个函数指定为一个参数

+ +

你可以指定一个函数作为第二个参数,在这种情况下,函数只有在匹配发生之后才会被调用。The function's result (return value) will be used as the replacement string. (Note: The above-mentioned special replacement patterns do not apply in this case.)

+ +

Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.

+ +

The arguments to the function are as follows:

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Possible nameSupplied value
matchThe matched substring. (Corresponds to $& above.)
p1, p2, ...The nth string found by a parenthesized capture group, provided the first argument to replace() was a {{jsxref("RegExp")}} object. (Corresponds to $1, $2, etc. above.) For example, if /(\a+)(\b+)/, was given, p1 is the match for \a+, and p2 for \b+.
offsetThe offset of the matched substring within the whole string being examined. (For example, if the whole string was 'abcd', and the matched substring was 'bc', then this argument will be 1.)
stringThe whole string being examined.
+ +

(The exact number of arguments depends on whether the first argument is a {{jsxref("RegExp")}} object—and, if so, how many parenthesized submatches it specifies.)

+ +

例子

+ +

使用 replaceAll

+ +
'aabbcc'.replaceAll('b', '.');
+// 'aa..cc'
+ +

非全局 regex 抛出

+ +

使用正则表达式搜索值时,它必须是全局的。这将行不通:

+ +
'aabbcc'.replaceAll(/b/, '.');
+TypeError: replaceAll must be called with a global RegExp
+
+ +

这将可以正常运行:

+ +
'aabbcc'.replaceAll(/b/g, '.');
+"aa..cc"
+
+ +

规范

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

浏览器兼容性

+ + + +

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

+ +

了解更多

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/search/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/search/index.html new file mode 100644 index 0000000000..66ab981508 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/search/index.html @@ -0,0 +1,87 @@ +--- +title: String.prototype.search() +slug: Web/JavaScript/Reference/Global_Objects/String/search +tags: + - JavaScript + - 原型 + - 参考 + - 字符串 + - 方法 + - 正则表达式 +translation_of: Web/JavaScript/Reference/Global_Objects/String/search +--- +
{{JSRef}}
+ +

search() 方法执行正则表达式和 {{jsxref("String")}} 对象之间的一个搜索匹配。

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

语法

+ +
str.search(regexp)
+ +

参数

+ +
+
regexp
+
一个{{jsxref("RegExp", "正则表达式(regular expression)")}}对象
+
如果传入一个非正则表达式对象 regexp,则会使用 new RegExp(regexp) 隐式地将其转换为正则表达式对象。
+
+ +

返回值

+ +

如果匹配成功,则 search() 返回正则表达式在字符串中首次匹配项的索引;否则,返回 -1

+ +

描述

+ +

当你想要知道字符串中是否存在某个模式(pattern)时可使用 search(),类似于正则表达式的 {{jsxref("RegExp.test", "test()")}} 方法。当要了解更多匹配信息时,可使用 {{jsxref("String.match", "match()")}}(但会更慢一些),该方法类似于正则表达式的 {{jsxref("RegExp.exec", "exec()")}} 方法。

+ +

示例

+ + + +

下面的例子中用两个不同的正则表达式对同一个字符串执行搜索匹配,得到一个成功匹配(正数返回值)和一个失败匹配(-1)。

+ +
var str = "hey JudE";
+var re = /[A-Z]/g;
+var re2 = /[.]/g;
+console.log(str.search(re)); // returns 4, which is the index of the first capital letter "J"
+console.log(str.search(re2)); // returns -1 cannot find '.' dot punctuation
+ +

规范

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

浏览器兼容性

+ + + +

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

+ +

Gecko 注意事项

+ + + +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/slice/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/slice/index.html new file mode 100644 index 0000000000..df8f398983 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/slice/index.html @@ -0,0 +1,122 @@ +--- +title: String.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/String/slice +tags: + - JavaScript + - Method + - Prototype + - String + - 原型 + - 字符串 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/String/slice +--- +
{{JSRef}}
+ +

slice() 方法提取某个字符串的一部分,并返回一个新的字符串,且不会改动原字符串。

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

语法

+ +
str.slice(beginIndex[, endIndex])
+ +

参数

+ +
+
beginIndex
+
从该索引(以 0 为基数)处开始提取原字符串中的字符。如果值为负数,会被当做 strLength + beginIndex 看待,这里的strLength 是字符串的长度(例如, 如果 beginIndex 是 -3 则看作是:strLength - 3
+
endIndex
+
可选。在该索引(以 0 为基数)处结束提取字符串。如果省略该参数,slice() 会一直提取到字符串末尾。如果该参数为负数,则被看作是 strLength + endIndex,这里的 strLength 就是字符串的长度(例如,如果 endIndex 是 -3,则是, strLength - 3)。
+
+ +

返回值

+ +

返回一个从原字符串中提取出来的新字符串

+ +

描述

+ +

slice() 从一个字符串中提取字符串并返回新字符串。在一个字符串中的改变不会影响另一个字符串。也就是说,slice 不会修改原字符串(只会返回一个包含了原字符串中部分字符的新字符串)。

+ +

slice() 提取的新字符串包括beginIndex但不包括 endIndex。下面有两个例子。

+ +

例 1:str.slice(1, 4) 提取第二个字符到第四个字符(被提取字符的索引值(index)依次为 1、2,和 3)。

+ +

例 2:str.slice(2, -1) 提取第三个字符到倒数第一个字符。

+ +

例子

+ +

使用 slice() 创建一个新的字符串

+ +

下面例子使用 slice() 创建了一个新字符串。

+ +
var str1 = 'The morning is upon us.', // str1 的长度 length 是 23。
+    str2 = str1.slice(1, 8),
+    str3 = str1.slice(4, -2),
+    str4 = str1.slice(12),
+    str5 = str1.slice(30);
+console.log(str2); // 输出:he morn
+console.log(str3); // 输出:morning is upon u
+console.log(str4); // 输出:is upon us.
+console.log(str5); // 输出:""
+
+ +

给 slice() 传入负值索引

+ +

下面的例子在使用 slice() 时传入了负值作为索引。

+ +
var str = 'The morning is upon us.';
+str.slice(-3);     // 返回 'us.'
+str.slice(-3, -1); // 返回 'us'
+str.slice(0, -1);  // 返回 'The morning is upon us'
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('ESDraft', '#sec-string.prototype.slice', 'String.prototype.slice')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-string.prototype.slice', 'String.prototype.slice')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-15.5.4.13', 'String.prototype.slice')}}{{Spec2('ES5.1')}}
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/small/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/small/index.html new file mode 100644 index 0000000000..7b55c68248 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/small/index.html @@ -0,0 +1,119 @@ +--- +title: String.prototype.small() +slug: Web/JavaScript/Reference/Global_Objects/String/small +translation_of: Web/JavaScript/Reference/Global_Objects/String/small +--- +
{{JSRef}} {{deprecated_header}}
+ +

small() 方法的作用是创建一个使字符串显示小号字体的 {{HTMLElement("small")}} 标签。

+ +

语法

+ +
str.small()
+ +

返回值

+ +

带有 {{HTMLElement("small")}} 标签的字符串。

+ +

描述

+ +

small() 方法会 将一个字符串嵌入到<small> 标签中: "<small>str</small>"。

+ +

示例

+ +

使用small()函数

+ +

为了改变一个字符串的字体大小,下面的例子使用了字符串中的方法:

+ +
var worldString = 'Hello, world';
+
+console.log(worldString.small());     // <small>Hello, world</small>
+console.log(worldString.big());       // <big>Hello, world</big>
+console.log(worldString.fontsize(7)); // <font size="7">Hello, world</fontsize>
+
+ +

使用{{domxref("HTMLElement.style", "element.style")}}对象,你能更加一般地获得和操作该元素的属性,比如:

+ +
document.getElementById('yourElemId').style.fontSize = '0.7em';
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.small', 'String.prototype.small')}}{{Spec2('ES6')}}初始定义。 在JavaScript 1.0中实现。在(规范性)附件B中定义了用于Web浏览器的附加ECMAScript 特性。
{{SpecName('ESDraft', '#sec-string.prototype.small', 'String.prototype.small')}}{{Spec2('ESDraft')}}在(规范性)附件B中定义了用于Web浏览器的附加ECMAScript 特性。
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/split/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/split/index.html new file mode 100644 index 0000000000..c1dee44c87 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/split/index.html @@ -0,0 +1,213 @@ +--- +title: String.prototype.split() +slug: Web/JavaScript/Reference/Global_Objects/String/split +tags: + - JavaScript + - Method + - Prototype + - Reference + - Regular Expressions + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/split +--- +

{{JSRef}}

+ +

split() 方法使用指定的分隔符字符串将一个{{jsxref("String")}}对象分割成子字符串数组,以一个指定的分割字串来决定每个拆分的位置。 

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

语法

+ +
str.split([separator[, limit]])
+
+ +
+

注意:如果使用空字符串(“)作为分隔符,则字符串不是在每个用户感知的字符(图形素集群)之间,也不是在每个Unicode字符(代码点)之间,而是在每个UTF-16代码单元之间。这会摧毁代理对。还请参见how do you get a string to a character array in javascript

+
+ +

参数

+ +
+
separator
+
指定表示每个拆分应发生的点的字符串。separator 可以是一个字符串或正则表达式。 如果纯文本分隔符包含多个字符,则必须找到整个字符串来表示分割点。如果在str中省略或不出现分隔符,则返回的数组包含一个由整个字符串组成的元素。如果分隔符为空字符串,则将str原字符串中每个字符的数组形式返回。
+
limit
+
一个整数,限定返回的分割片段数量。当提供此参数时,split 方法会在指定分隔符的每次出现时分割该字符串,但在限制条目已放入数组时停止。如果在达到指定限制之前达到字符串的末尾,它可能仍然包含少于限制的条目。新数组中不返回剩下的文本。
+
+ +

返回值

+ +

返回源字符串以分隔符出现位置分隔而成的一个 {{jsxref("Array")}} 

+ +

描述

+ +

找到分隔符后,将其从字符串中删除,并将子字符串的数组返回。如果没有找到或者省略了分隔符,则该数组包含一个由整个字符串组成的元素。如果分隔符为空字符串,则将str转换为字符数组。如果分隔符出现在字符串的开始或结尾,或两者都分开,分别以空字符串开头,结尾或两者开始和结束。因此,如果字符串仅由一个分隔符实例组成,则该数组由两个空字符串组成。

+ +

如果分隔符是包含捕获括号的正则表达式,则每次分隔符匹配时,捕获括号的结果(包括任何未定义的结果)将被拼接到输出数组中。但是,并不是所有浏览器都支持此功能。

+ +

{{Note("当字符串为空时,split()返回一个包含一个空字符串的数组,而不是一个空数组,如果字符串和分隔符都是空字符串,则返回一个空数组。")}}

+ +

示例

+ +

使用 split()

+ +

下例定义了一个函数:根据指定的分隔符将一个字符串分割成一个字符串数组。分隔字符串后,该函数依次输出原始字符串信息,被使用的分隔符,返回数组元素的个数,以及返回数组中所有的元素。

+ +
function splitString(stringToSplit, separator) {
+  var arrayOfStrings = stringToSplit.split(separator);
+
+  console.log('The original string is: "' + stringToSplit + '"');
+  console.log('The separator is: "' + separator + '"');
+  console.log("The array has " + arrayOfStrings.length + " elements: ");
+
+  for (var i=0; i < arrayOfStrings.length; i++)
+    console.log(arrayOfStrings[i] + " / ");
+}
+
+var tempestString = "Oh brave new world that has such people in it.";
+var monthString = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";
+
+var space = " ";
+var comma = ",";
+
+splitString(tempestString, space);
+splitString(tempestString);
+splitString(monthString, comma);
+
+ +

上例输出下面结果:

+ +
The original string is: "Oh brave new world that has such people in it."
+The separator is: " "
+The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it. /
+
+The original string is: "Oh brave new world that has such people in it."
+The separator is: "undefined"
+The array has 1 elements: Oh brave new world that has such people in it. /
+
+The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
+The separator is: ","
+The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec /
+
+ +

移出字符串中的空格

+ +

下例中,split() 方法会查找“0 或多个空白符接着的分号,再接着 0 或多个空白符”模式的字符串,找到后,就将空白符从字符串中移除,nameListsplit 的返回数组。

+ +
var names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ";
+
+console.log(names);
+
+var re = /\s*(?:;|$)\s*/;
+var nameList = names.split(re);
+
+console.log(nameList);
+
+ +

上例输出两行,第一行输出原始字符串,第二行输出结果数组。

+ +
Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand
+[ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand", "" ]
+
+ +

限制返回值中分割元素数量

+ +

下例中,split 查找字符串中的 0 或多个空格,并返回找到的前 3 个分割元素(splits)。

+ +
var myString = "Hello World. How are you doing?";
+var splits = myString.split(" ", 3);
+
+console.log(splits);
+
+ +

上例输出:

+ +
["Hello", "World.", "How"]
+ +

靠正则来分割使结果中包含分隔块

+ +

如果 separator 包含捕获括号(capturing parentheses),则其匹配结果将会包含在返回的数组中。

+ +
var myString = "Hello 1 word. Sentence number 2.";
+var splits = myString.split(/(\d)/);
+
+console.log(splits);
+
+ +

上例输出:

+ +
[ "Hello ", "1", " word. Sentence number ", "2", "." ]
+ +

使用一个数组来作为分隔符

+ +
const myString = 'this|is|a|Test';
+const splits = myString.split(['|']);
+
+console.log(splits); //["this", "is", "a", "Test"]
+
+const myString = 'ca,bc,a,bca,bca,bc';
+
+const splits = myString.split(['a','b']);
+// myString.split(['a','b']) is same as myString.split(String(['a','b']))
+
+console.log(splits);  //["c", "c,", "c", "c", "c"]
+ +

用split()来颠倒字符串顺序

+ +
+

注意这并非一种很健壮的逆转字符串的方法:

+ +
const str = 'asdfghjkl';
+const strReverse = str.split('').reverse().join(''); // 'lkjhgfdsa'
+// split() returns an array on which reverse() and join() can be applied
+ +

如果字符串包含图形素集群,即使使用Unicode感知的拆分(use for example esrever instead),也不能工作。

+ +
const str = 'résumé';
+const strReverse = str.split(/(?:)/u).reverse().join('');
+// => "́emuśer"
+ +

Bonus: use {{jsxref("Operators/Comparison_Operators", "===", "#Identity_strict_equality_(===)")}} operator to test if the original string was palindrome.

+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 3rd Edition.StandardInitial definition.
+ Implemented in JavaScript 1.1
{{SpecName('ES5.1', '#sec-15.5.4.14', 'String.prototype.split')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.split', 'String.prototype.split')}}{{Spec2('ES6')}}
+ +

浏览器兼容性

+ +

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

+ +

相关链接

+ + 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")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/strike/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/strike/index.html new file mode 100644 index 0000000000..3e904a9651 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/strike/index.html @@ -0,0 +1,116 @@ +--- +title: String.prototype.strike() +slug: Web/JavaScript/Reference/Global_Objects/String/strike +translation_of: Web/JavaScript/Reference/Global_Objects/String/strike +--- +
{{JSRef}} {{deprecated_header}}
+ +

strike()方法创建{{HTMLElement("strike")}} HTML 元素,使字符串展示为被删除的文本。

+ +

语法

+ +
str.strike()
+ +

返回值

+ +

包含{{HTMLElement("strike")}} HTML 元素的字符串。

+ +

描述

+ +

strike()方法将字符串嵌入<strike>标签: "<strike>str</strike>".

+ +

示例

+ +

使用strike()

+ +

下面的示例使用字符串方法来修改字符串的格式:

+ +
var worldString = 'Hello, world';
+
+console.log(worldString.blink()); // <blink>Hello, world</blink>
+console.log(worldString.bold()); // <b>Hello, world</b>
+console.log(worldString.italics()); // <i>Hello, world</i>
+console.log(worldString.strike()); // <strike>Hello, world</strike>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.strike', 'String.prototype.strike')}}{{Spec2('ES6')}}初始定义。在 JavaScript 1.0 中实现。 在(规范性)附件 B 中定义为用于 Web 浏览器的 ECMAScript 附加特性。
{{SpecName('ESDraft', '#sec-string.prototype.strike', 'String.prototype.strike')}}{{Spec2('ESDraft')}}在(规范性)附件 B 中定义为用于 Web 浏览器的 ECMAScript 附加特性。
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

另见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/sub/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/sub/index.html new file mode 100644 index 0000000000..8c47471d25 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/sub/index.html @@ -0,0 +1,119 @@ +--- +title: String.prototype.sub() +slug: Web/JavaScript/Reference/Global_Objects/String/sub +tags: + - String.sub() + - 已废弃 +translation_of: Web/JavaScript/Reference/Global_Objects/String/sub +--- +
{{JSRef}} {{deprecated_header}}
+ +

sub()方法创建一个 {{HTMLElement("sub")}} HTML 元素,使字符串展示为下标。

+ +

语法

+ +
str.sub()
+ +

返回值

+ +

包含{{HTMLElement("sub")}} HTML 元素的字符串。

+ +

描述

+ +

sub()方法将字符串嵌入<sub>标签: "<sub>str</sub>".

+ +

示例

+ +

使用sub()sup()方法

+ +

下面的示例使用了sub()和{{jsxref("String.prototype.sup()", "sup()")}}方法来格式化字符串:

+ +
var superText = 'superscript';
+var subText = 'subscript';
+
+console.log('This is what a ' + superText.sup() + ' looks like.');
+// 这就是<sup>superscript</sup>的样子。
+
+console.log('This is what a ' + subText.sub() + ' looks like.');
+// 这就是<sub>subscript</sub>的样子。
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.sub', 'String.prototype.sub')}}{{Spec2('ES6')}}初始定义。在 JavaScript 1.0 中实现。在(规范性)附件 B 中定义为用于 Web 浏览器的 ECMAScript 附加特性。
{{SpecName('ESDraft', '#sec-string.prototype.sub', 'String.prototype.sub')}}{{Spec2('ESDraft')}}在(规范性)附件 B 中定义为用于 Web 浏览器的 ECMAScript 附加特性。
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

另见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/substr/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/substr/index.html new file mode 100644 index 0000000000..8faa458218 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/substr/index.html @@ -0,0 +1,166 @@ +--- +title: String.prototype.substr() +slug: Web/JavaScript/Reference/Global_Objects/String/substr +tags: + - String.prototype.substr() +translation_of: Web/JavaScript/Reference/Global_Objects/String/substr +--- +

{{JSRef}}

+ +
警告: 尽管 String.prototype.substr(…) 没有严格被废弃 (as in "removed from the Web standards"), 但它被认作是遗留的函数并且可以的话应该避免使用。它并非JavaScript核心语言的一部分,未来将可能会被移除掉。如果可以的话,使用 substring() 替代它.
+ +

substr() 方法返回一个字符串中从指定位置开始到指定字符数的字符。

+ +

语法

+ +
str.substr(start[, length])
+ +

参数

+ +
+
start
+
开始提取字符的位置。如果为负值,则被看作 strLength + start,其中 strLength 为字符串的长度(例如,如果 start-3,则被看作 strLength + (-3))。
+
+ +
+
length
+
可选。提取的字符数。
+
+ +

描述

+ +

start 是一个字符的索引。首字符的索引为 0,最后一个字符的索引为 字符串的长度减去1。substrstart 位置开始提取字符,提取 length 个字符(或直到字符串的末尾)。

+ +

如果 start 为正值,且大于或等于字符串的长度,则 substr 返回一个空字符串。

+ +

如果 start 为负值,则 substr 把它作为从字符串末尾开始的一个字符索引。如果 start 为负值且 abs(start) 大于字符串的长度,则 substr 使用 0 作为开始提取的索引。注意负的 start 参数不被 Microsoft JScript 所支持。

+ +

如果 length 为 0 或负值,则 substr 返回一个空字符串。如果忽略 length,则 substr 提取字符,直到字符串末尾。

+ +

示例

+ +

例子:使用 substr

+ +
var str = "abcdefghij";
+
+console.log("(1,2): "    + str.substr(1,2));   // (1,2): bc
+console.log("(-3,2): "   + str.substr(-3,2));  // (-3,2): hi
+console.log("(-3): "     + str.substr(-3));    // (-3): hij
+console.log("(1): "      + str.substr(1));     // (1): bcdefghij
+console.log("(-20, 2): " + str.substr(-20,2)); // (-20, 2): ab
+console.log("(20, 2): "  + str.substr(20,2));  // (20, 2):
+
+ +

兼容旧环境(Polyfill)

+ +

Microsoft's JScript 不支持负的 start 索引。如果你想充分利用该方法的功能,则需要使用下面的兼容性代码修复此 bug:

+ +
// only run when the substr function is broken
+if ('ab'.substr(-1) != 'b')
+{
+  /**
+   *  Get the substring of a string
+   *  @param  {integer}  start   where to start the substring
+   *  @param  {integer}  length  how many characters to return
+   *  @return {string}
+   */
+  String.prototype.substr = function(substr) {
+    return function(start, length) {
+      // did we get a negative start, calculate how much it is
+      // from the beginning of the string
+      if (start < 0) start = this.length + start;
+
+      // call the original function
+      return substr.call(this, start, length);
+    }
+  }(String.prototype.substr);
+}
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 3rd Edition.StandardDefined in the (informative) Compatibility Annex B.
+ Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-B.2.3', 'String.prototype.substr')}}{{Spec2('ES5.1')}}Defined in the (informative) Compatibility Annex B
{{SpecName('ES6', '#sec-string.prototype.substr', 'String.prototype.substr')}}{{Spec2('ES6')}}Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Note: Up to version 3.6, Firefox had a bug which caused substr to return empty result when an explicit undefined value was passed in as the length.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/substring/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/substring/index.html new file mode 100644 index 0000000000..9a2d97f935 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/substring/index.html @@ -0,0 +1,194 @@ +--- +title: String.prototype.substring() +slug: Web/JavaScript/Reference/Global_Objects/String/substring +tags: + - String.prototype.substring() +translation_of: Web/JavaScript/Reference/Global_Objects/String/substring +--- +

{{JSRef}}

+ +

substring() 方法返回一个字符串在开始索引到结束索引之间的一个子集, 或从开始索引直到字符串的末尾的一个子集。

+ +

语法

+ +
str.substring(indexStart[, indexEnd])
+ +

参数

+ +
+
indexStart
+
需要截取的第一个字符的索引,该索引位置的字符作为返回的字符串的首字母。
+
indexEnd
+
可选。一个 0 到字符串长度之间的整数,以该数字为索引的字符不包含在截取的字符串内。
+
+ +

返回值

+ +

包含给定字符串的指定部分的新字符串。

+ +

描述

+ +

substring 提取从 indexStart 到 indexEnd(不包括)之间的字符。特别地:

+ + + +

示例

+ +

例子:使用 substring

+ +

下例使用 substring 输出字符串 "Mozilla" 中的字符:

+ +
var anyString = "Mozilla";
+
+// 输出 "Moz"
+console.log(anyString.substring(0,3));
+console.log(anyString.substring(3,0));
+console.log(anyString.substring(3,-3));
+console.log(anyString.substring(3,NaN));
+console.log(anyString.substring(-2,3));
+console.log(anyString.substring(NaN,3));
+
+// 输出 "lla"
+console.log(anyString.substring(4,7));
+console.log(anyString.substring(7,4));
+
+// 输出 ""
+console.log(anyString.substring(4,4));
+
+// 输出 "Mozill"
+console.log(anyString.substring(0,6));
+
+// 输出 "Mozilla"
+console.log(anyString.substring(0,7));
+console.log(anyString.substring(0,10));
+
+ +

运用 length 属性来使用 substring()

+ +

下面一个例子运用了    String.length 属性去获取指定字符串的倒数元素。显然这个办法更容易记住,因为你不再像上面那个例子那样去记住起始位置和最终位置。

+ +
// Displays 'illa' the last 4 characters
+var anyString = 'Mozilla';
+var anyString4 = anyString.substring(anyString.length - 4);
+console.log(anyString4);
+
+// Displays 'zilla' the last 5 characters
+var anyString = 'Mozilla';
+var anyString5 = anyString.substring(anyString.length - 5);
+console.log(anyString5);
+ +

例子:替换一个字符串的子字符串

+ +

下例替换了一个字符串中的子字符串。可以替换单个字符和子字符串。该例结尾调用的函数将 "Brave New World" 变成了 "Brave New Web"。

+ +
function replaceString(oldS, newS, fullS) {
+// Replaces oldS with newS in the string fullS
+  for (var i = 0; i < fullS.length; i++) {
+    if (fullS.substring(i, i + oldS.length) == oldS) {
+     fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length, fullS.length);
+    }
+  }
+  return fullS;
+}
+
+replaceString("World", "Web", "Brave New World");
+ +

需要注意的是,如果 oldSnewS 的子字符串将会导致死循环。例如,尝试把 "Web" 替换成 "OtherWorld"。一个更好的方法如下:

+ +
function replaceString(oldS, newS,fullS){
+  return fullS.split(oldS).join(newS);
+}
+ +

上面的代码只是子字符串操作的一个例子。如果你需要替换子字符串,更多时候会用到 {{jsxref("String.prototype.replace()")}}。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardImplemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-15.5.4.15', 'String.prototype.substring')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.substring', 'String.prototype.substring')}}{{Spec2('ES6')}}
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/sup/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/sup/index.html new file mode 100644 index 0000000000..118bbd1f2e --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/sup/index.html @@ -0,0 +1,118 @@ +--- +title: String.prototype.sup() +slug: Web/JavaScript/Reference/Global_Objects/String/sup +tags: + - String.prototype.sup() +translation_of: Web/JavaScript/Reference/Global_Objects/String/sup +--- +
{{JSRef}} {{deprecated_header}}
+ +

sup()方法创建 一个{{HTMLElement("sup")}}HTML 元素,使字符串显示为上标。

+ +

语法

+ +
str.sup()
+ +

返回值

+ +

包含{{HTMLElement("sup")}} HTML 元素的字符串。

+ +

描述

+ +

sup() 方法将字符串嵌入 <sup> 标签中:"<sup>str</sup>".

+ +

示例

+ +

使用sub()sup()方法

+ +

下面的示例使用了{{jsxref("String.prototype.sub()", "sub()")}}和sup()方法来格式化字符串:

+ +
var superText = 'superscript';
+var subText = 'subscript';
+
+console.log('This is what a ' + superText.sup() + ' looks like.');
+// "这就是<sup>superscript</sup>的样子。"
+
+console.log('This is what a ' + subText.sub() + ' looks like.');
+// "这就是<sub>subscript</sub>的样子。"
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.sup', 'String.prototype.sup')}}{{Spec2('ES6')}}初始定义。在 JavaScript 1.0 中实现。在(规范性)附件 B 中定义为用于 Web 浏览器的 ECMAScript 附加特性。
{{SpecName('ESDraft', '#sec-string.prototype.sup', 'String.prototype.sup')}}{{Spec2('ESDraft')}}在(规范性)附件 B 中定义为用于 Web 浏览器的 ECMAScript 附加特性。
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

另见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/tolocalelowercase/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/tolocalelowercase/index.html new file mode 100644 index 0000000000..a9709187a7 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/tolocalelowercase/index.html @@ -0,0 +1,145 @@ +--- +title: String.prototype.toLocaleLowerCase() +slug: Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase +translation_of: Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase +--- +
{{JSRef}}
+ +

toLocaleLowerCase()方法根据任何指定区域语言环境设置的大小写映射,返回调用字符串被转换为小写的格式。

+ +

语法

+ +
str.toLocaleLowerCase()
+str.toLocaleLowerCase(locale)
+str.toLocaleLowerCase([locale, locale, ...])
+ +

参数

+ +
+
locale {{optional_inline}}
+
参数 locale 指明要转换成小写格式的特定语言区域。 如果以一个数组 {{jsxref("Array")}}形式给出多个locales,  最合适的地区将被选出来应用(参见best available locale)。默认的locale是主机环境的当前区域(locale)设置。
+
+ +

返回值

+ +

根据任何特定于语言环境的案例映射规则将被调用字串转换成小写格式的一个新字符串。

+ +

Exceptions

+ + + +

描述

+ +

toLocaleLowerCase() 方法返回根据任意区域语言大小写映射集而转换成小写格式的字符串。toLocaleLowerCase() 并不会影响字符串原本的值。在大多数情况下,该方法和调用 {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}}的结果相同,但是在某些区域环境中,比如土耳其语,它的大小写映射并不遵循在Unicode中的默认的大小写映射,因此会有一个不同的结果。

+ +

例子

+ +

使用toLocaleLowerCase()

+ +
'ALPHABET'.toLocaleLowerCase(); // 'alphabet'
+
+'\u0130'.toLocaleLowerCase('tr') === 'i';    // true
+'\u0130'.toLocaleLowerCase('en-US') === 'i'; // false
+
+let locales = ['tr', 'TR', 'tr-TR', 'tr-u-co-search', 'tr-x-turkish'];
+'\u0130'.toLocaleLowerCase(locales) === 'i'; // true
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.17', 'String.prototype.toLocaleLowerCase')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.tolocalelowercase', 'String.prototype.toLocaleLowerCase')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.tolocalelowercase', 'String.prototype.toLocaleLowerCase')}}{{Spec2('ESDraft')}}
{{SpecName('ES Int Draft', '#sup-string.prototype.tolocalelowercase', 'String.prototype.toLocaleLowerCase')}}{{Spec2('ES Int Draft')}}ES Intl 2017 added the localeparameter.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

参阅

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/tolocaleuppercase/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/tolocaleuppercase/index.html new file mode 100644 index 0000000000..9043db95c5 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/tolocaleuppercase/index.html @@ -0,0 +1,91 @@ +--- +title: String.prototype.toLocaleUpperCase() +slug: Web/JavaScript/Reference/Global_Objects/String/toLocaleUpperCase +translation_of: Web/JavaScript/Reference/Global_Objects/String/toLocaleUpperCase +--- +
{{JSRef}}
+ +

toLocaleUpperCase() 方法根据本地主机语言环境把字符串转换为大写格式,并返回转换后的字符串。

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

语法

+ +
str.toLocaleUpperCase()
+str.toLocaleUpperCase(locale)
+str.toLocaleUpperCase([locale, locale, ...])
+
+ +

参数

+ +
+
locale {{optional_inline}}
+
The locale parameter indicates the locale to be used to convert to upper case according to any locale-specific case mappings. If multiple locales are given in an {{jsxref("Array")}}, the best available locale is used. The default locale is the host environment’s current locale.
+
+ +

返回值

+ +

A new string representing the calling string converted to upper case, according to any locale-specific case mappings.

+ +

Exceptions

+ + + +

描述

+ +

The toLocaleUpperCase() method returns the value of the string converted to upper case according to any locale-specific case mappings. toLocaleUpperCase() does not affect the value of the string itself. In most cases, this will produce the same result as {{jsxref("String.prototype.toUpperCase()", "toUpperCase()")}}, but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result.

+ +

Also notice that conversion is not necessarily a 1:1 character mapping, as some characters might result in two (or even more) characters when transformed to upper-case. Therefore the length of the result string can differ from the input length. This also implies that the conversion is not stable, so i.E. the following can return false:
+ x.toLocaleLowerCase() === x.toLocaleUpperCase().toLocaleLowerCase()

+ +

例子

+ +

使用 toLocaleUpperCase()

+ +
'alphabet'.toLocaleUpperCase(); // 'ALPHABET'
+
+'Gesäß'.toLocaleUpperCase(); // 'GESÄSS'
+
+'i\u0307'.toLocaleUpperCase('lt-LT'); // 'I'
+
+let locales = ['lt', 'LT', 'lt-LT', 'lt-u-co-phonebk', 'lt-x-lietuva'];
+'i\u0307'.toLocaleUpperCase(locales); // 'I'
+ +

规范

+ + + + + + + + + + + + + +
规范
{{SpecName('ESDraft', '#sec-string.prototype.tolocaleuppercase', 'String.prototype.toLocaleUpperCase')}}
{{SpecName('ES Int Draft', '#sup-string.prototype.tolocaleuppercase', 'String.prototype.toLocaleUpperCase')}}
+ +

浏览器兼容性

+ + + +

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

+ +

相关链接

+ + + +
+
+
diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/tolowercase/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/tolowercase/index.html new file mode 100644 index 0000000000..e08a47bb55 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/tolowercase/index.html @@ -0,0 +1,136 @@ +--- +title: String.prototype.toLowerCase() +slug: Web/JavaScript/Reference/Global_Objects/String/toLowerCase +tags: + - JavaScript + - Method + - Prototype + - String + - toLowerCase() +translation_of: Web/JavaScript/Reference/Global_Objects/String/toLowerCase +--- +
{{JSRef}}
+ +

toLowerCase() 会将调用该方法的字符串值转为小写形式,并返回。

+ +

语法

+ +
str.toLowerCase()
+
+ +

+ +

返回值

+ +

一个新的字符串,表示转换为小写的调用字符串。

+ +

描述

+ +

toLowerCase 会将调用该方法的字符串值转为小写形式,并返回。toLowerCase 不会影响字符串本身的值。

+ +

示例

+ +

例子:使用 toLowerCase()

+ +
console.log('中文简体 zh-CN || zh-Hans'.toLowerCase());
+// 中文简体 zh-cn || zh-hans
+
+​console.log( "ALPHABET".toLowerCase() );
+// "alphabet"
+ +
+ +

说明

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.16', 'String.prototype.toLowerCase')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}{{Spec2('ESDraft')}} 
+  
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/tosource/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/tosource/index.html new file mode 100644 index 0000000000..7914776a25 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/tosource/index.html @@ -0,0 +1,91 @@ +--- +title: String.prototype.toSource() +slug: Web/JavaScript/Reference/Global_Objects/String/toSource +translation_of: Web/JavaScript/Reference/Global_Objects/String/toSource +--- +
{{JSRef}} {{non-standard_header}}
+ +

toSource() 方法返回一个代表对象的源代码。

+ +

语法

+ +
String.toSource()
+str.toSource()
+
+ +

描述

+ +

toSource() 方法返回以下值:

+ +

对于内建对象 {{jsxref("String")}} , toSource()返回以下值说明源码不可用:

+ +
function String() {
+    [native code]
+}
+
+ +

对于实例{{jsxref("String")}} 或者字符串, toSource() 返回一个字符串表示源码.

+ +

这种方法通常在内部被JavaScript调用,而不是明确的代码。.

+ +

规范

+ +

不属于任何标准. 在 JavaScript 1.3实现了.

+ +

浏览器适配

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/tostring/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/tostring/index.html new file mode 100644 index 0000000000..192ae75b12 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/tostring/index.html @@ -0,0 +1,124 @@ +--- +title: String.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/String/toString +translation_of: Web/JavaScript/Reference/Global_Objects/String/toString +--- +
{{JSRef("Global_Objects", "String")}}
+ +

概述

+ +

toString() 方法返回指定对象的字符串形式。

+ +

语法

+ +
str.toString()
+
+ +

返回值

+ +

一个表示调用对象的字符串。

+ +

描述

+ +

String 对象覆盖了{{jsxref("Global_Objects/Object", "Object")}} 对象的 toString 方法;并没有继承 {{jsxref("Object.toString()")}}。对于 String 对象,toString 方法返回该对象的字符串形式,和 {{jsxref("String.prototype.valueOf()")}} 方法返回值一样。

+ +

示例

+ +

例子:使用 toString

+ +

下例输出一个字符串对象(String object)的字符串值:

+ +
var x = new String("Hello world");
+
+alert(x.toString())      // 输出 "Hello world"
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.5.4.2', 'String.prototype.toString')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.tostring', 'String.prototype.toString')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.tostring', 'String.prototype.toString')}}{{Spec2('ESDraft')}}
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/touppercase/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/touppercase/index.html new file mode 100644 index 0000000000..7d0edf43c5 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/touppercase/index.html @@ -0,0 +1,87 @@ +--- +title: String.prototype.toUpperCase() +slug: Web/JavaScript/Reference/Global_Objects/String/toUpperCase +tags: + - JavaScript + - 原型 + - 字符串 + - 引用 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/String/toUpperCase +--- +
{{JSRef}}
+ +

toUpperCase() 方法将调用该方法的字符串转为大写形式并返回(如果调用该方法的值不是字符串类型会被强制转换)。

+ +
{{EmbedInteractiveExample("pages/js/string-touppercase.html","shorter")}}
+ + + +

语法

+ +
str.toUpperCase()
+ +

返回值

+ +

一个新的字符串,表示转换为大写的调用字符串。

+ +

错误处理

+ +
+
{{jsxref("TypeError(类型错误)")}}
+
在 {{jsxref("null")}} 或 {{jsxref("undefined")}}类型上调用,例如:String.prototype.toUpperCase.call(undefined).
+
+ +

描述

+ +

toUpperCase() 返回转为大写形式的字符串。此方法不会影响原字符串本身的值,因为JavaScript中字符串的值是不可改变的。

+ +

示例

+ +

基本用法

+ +
console.log('alphabet'.toUpperCase()); // 'ALPHABET'
+
+ +

将非字符串类型的 this (上下文)转为字符串

+ +

此方法会将任何非字符串类型的值转为字符串, 当你将其上下文 this 值设置为非字符串类型

+ +
const a = String.prototype.toUpperCase.call({
+  toString: function toString() {
+    return 'abcdef';
+  }
+});
+
+const b = String.prototype.toUpperCase.call(true);
+
+// 输出 'ABCDEF TRUE'。
+console.log(a, b);
+
+ +

规范

+ + + + + + + + + + +
规范
{{SpecName('ESDraft', '#sec-string.prototype.touppercase', 'String.prototype.toUpperCase')}}
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/trim/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/trim/index.html new file mode 100644 index 0000000000..66e0d5171f --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/trim/index.html @@ -0,0 +1,103 @@ +--- +title: String.prototype.trim() +slug: Web/JavaScript/Reference/Global_Objects/String/Trim +tags: + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - String + - 参考 + - 字符串 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/String/Trim +--- +
+
+
{{JSRef}}
+
+
+ +

trim() 方法会从一个字符串的两端删除空白字符。在这个上下文中的空白字符是所有的空白字符 (space, tab, no-break space 等) 以及所有行终止符字符(如 LF,CR等)。

+ +

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

+ + + +

语法

+ +
str.trim()
+ +

返回值

+ +

一个代表调用字符串两端去掉空白的新字符串。

+ +

描述

+ +

trim() 方法返回一个从两头去掉空白字符的字符串,并不影响原字符串本身。

+ +

例子

+ +

使用 trim()

+ +

下面的例子中将显示小写的字符串 'foo':

+ +
var orig = '   foo  ';
+console.log(orig.trim()); // 'foo'
+
+// 另一个 .trim() 例子,只从一边删除
+
+var orig = 'foo    ';
+console.log(orig.trim()); // 'foo'
+
+ +

兼容旧环境

+ +

如果 trim() 不存在,可以在所有代码前执行下面代码

+ +
if (!String.prototype.trim) {
+  String.prototype.trim = function () {
+    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
+  };
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('ES5.1', '#sec-15.5.4.20', 'String.prototype.trim')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.1.
{{SpecName('ES6', '#sec-string.prototype.trim', 'String.prototype.trim')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.trim', 'String.prototype.trim')}}{{Spec2('ESDraft')}}
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/trimleft/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/trimleft/index.html new file mode 100644 index 0000000000..bc6133cecb --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/trimleft/index.html @@ -0,0 +1,122 @@ +--- +title: String.prototype.trimStart() +slug: Web/JavaScript/Reference/Global_Objects/String/TrimLeft +tags: + - JavaScript + - Method + - Prototype + - String + - 参考 + - 字符串 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/String/trimStart +--- +
{{JSRef}}
+ +
trimStart() 方法从字符串的开头删除空格。trimLeft() 是此方法的别名。
+ +
{{EmbedInteractiveExample("pages/js/string-trimstart.html")}}
+ + + +

语法

+ +
str.trimStart();
+str.trimLeft();
+ +

返回值

+ +

一个新字符串,表示从其开头(左端)除去空格的调用字符串。

+ +

描述

+ +

trimStart() / trimLeft() 方法移除原字符串左端的连续空白符并返回一个新字符串,并不会直接修改原字符串本身。

+ +

别名

+ +

为了与 {{jsxref("String.prototype.padStart")}} 等函数保持一致,标准方法名称为trimStart。 但是,出于 Web 兼容性原因,trimLeft 仍然是 trimStart 的别名。在某些引擎中,这意味着:

+ +
String.prototype.trimLeft.name === "trimStart";
+ +

示例

+ +

使用 trimStart()

+ +

下面的例子输出了小写的字符串 "foo  "

+ +
var str = "   foo  ";
+
+console.log(str.length); // 8
+
+str = str.trimStart()    // 等同于 str = str.trimLeft();
+console.log(str.length); // 5
+console.log(str);        // "foo  "
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
String.prototype.{trimStart,trimEnd}proposalStage 4Expected to be part of ES2019
+ +

浏览器兼容性

+ + + +

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

+ +

Polyfill

+ +
// https://github.com/FabioVergani/js-Polyfill_String-trimStart
+
+(function(w){
+    var String=w.String, Proto=String.prototype;
+
+    (function(o,p){
+        if(p in o?o[p]?false:true:true){
+            var r=/^\s+/;
+            o[p]=o.trimLeft||function(){
+                return this.replace(r,'')
+            }
+        }
+    })(Proto,'trimStart');
+
+})(window);
+
+
+/*
+ES6:
+(w=>{
+    const String=w.String, Proto=String.prototype;
+
+    ((o,p)=>{
+        if(p in o?o[p]?false:true:true){
+            const r=/^\s+/;
+            o[p]=o.trimLeft||function(){
+                return this.replace(r,'')
+            }
+        }
+    })(Proto,'trimStart');
+
+})(window);
+*/
+ +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/trimright/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/trimright/index.html new file mode 100644 index 0000000000..9c8319cb29 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/trimright/index.html @@ -0,0 +1,84 @@ +--- +title: String.prototype.trimRight() +slug: Web/JavaScript/Reference/Global_Objects/String/TrimRight +tags: + - JavaScript + - Method + - Prototype + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/trimEnd +--- +
{{JSRef}}
+ +

trimEnd() 方法从一个字符串的末端移除空白字符。trimRight() 是这个方法的别名。

+ +

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

+ +

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

+ +

语法

+ +
str.trimEnd();
+str.trimRight();
+ +

返回值

+ +

一个新字符串,表示从调用字串的末(右)端除去空白。

+ +

描述

+ +

trimEnd() / trimRight()方法移除原字符串右端的连续空白符并返回,trimEnd() / trimRight()方法并不会直接修改原字符串本身。

+ +

别名

+ +

为了与 {{jsxref("String.prototype.padEnd")}} 等函数保持一致,标准方法名称为trimEnd。 但是,出于Web兼容性原因,trimRight仍然是trimEnd的别名。 在某些引擎中,这意味着:

+ +
String.prototype.trimRight.name === "trimEnd";
+
+ +

示例

+ +

使用trimEnd()

+ +

下面的例子输出了小写的字符串"   foo":

+ +
var str = "   foo  ";
+
+alert(str.length); // 8
+
+str = str.trimRight();  // 或写成str = str.trimEnd();
+console.log(str.length); // 6
+console.log(str);       // '   foo'
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
String.prototype.{trimStart,trimEnd}proposalStage 4Expected to be part of ES2019
+ +

Browser compatibility

+ +

The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

+ +

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

+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/valueof/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/valueof/index.html new file mode 100644 index 0000000000..7697c1074d --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/valueof/index.html @@ -0,0 +1,58 @@ +--- +title: String.prototype.valueOf() +slug: Web/JavaScript/Reference/Global_Objects/String/valueOf +translation_of: Web/JavaScript/Reference/Global_Objects/String/valueOf +--- +
{{JSRef}}
+ +

valueOf() 方法返回  {{jsxref("String")}}  对象的原始值

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

语法

+ +
str.valueOf()
+ +

返回结果

+ +

A string representing the primitive value of a given {{jsxref("String")}} object.

+ +

描述

+ +

The valueOf() method of {{jsxref("String")}} returns the primitive value of a {{jsxref("String")}} object as a string data type. This value is equivalent to {{jsxref("String.prototype.toString()")}}.

+ +

此方法通常由JavaScript在内部调用,而不是在代码中显式调用。

+ +

示例

+ +

使用 valueOf()

+ +
var x = new String('Hello world');
+console.log(x.valueOf()); // Displays 'Hello world'
+
+ +

规范

+ + + + + + + + + + +
规范
{{SpecName('ESDraft', '#sec-string.prototype.valueof', 'String.prototype.valueOf')}}
+ +

浏览器兼容性

+ + + +

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

+ +

参见

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