diff options
Diffstat (limited to 'files/zh-cn/web/javascript/reference/global_objects/string')
54 files changed, 7570 insertions, 0 deletions
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 +--- +<div>{{JSRef}}</div> + +<p><strong><code>[@@iterator]()</code></strong> 方法返回一个新的Iterator对象,它遍历字符串的代码点,返回每一个代码点的字符串值。</p> + +<p>{{EmbedInteractiveExample("pages/js/string-iterator.html")}}</p> + +<p>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 <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code><var>string</var>[Symbol.iterator]</code></pre> + +<h3 id="返回值">返回值</h3> + +<p>一个新的Iterator对象。</p> + +<h2 id="示例">示例</h2> + +<h3 id="使用iterator"><code>使用[@@iterator]()</code></h3> + +<pre class="brush:js">var string = 'A\uD835\uDC68'; + +var strIter = string[Symbol.iterator](); + +console.log(strIter.next().value); // "A" +console.log(strIter.next().value); // "\uD835\uDC68" +</pre> + +<h3 id="通过_for..of_使用iterator"><code>通过</code> <code>for..of 使用[@@iterator]()</code></h3> + +<pre class="brush:js">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" +</pre> + +<h2 id="规范">规范</h2> + +<table> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-string.prototype-@@iterator', 'String.prototype[@@iterator]()')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype-@@iterator', 'String.prototype[@@iterator]()')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <tbody> + <tr> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>基本支持</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("36")}} [1]</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>基本支持</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("36")}} [1]</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[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 <code>iterator</code> property was used (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=907077">bug 907077</a>), and from Gecko 27 to Gecko 35 the <code>"@@iterator"</code> placeholder was used. In Gecko 36 (Firefox 36 / Thunderbird 36 / SeaMonkey 2.33), the <code>@@iterator</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol">symbol</a> got implemented (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=918828">bug 918828</a>).</p> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">Iteration protocols</a></li> +</ul> 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 +--- +<div>{{JSRef("Global_Objects", "String")}}</div> + +<h2 id="概述">概述</h2> + +<div class="blockIndicator warning"> +<p>已废弃<br> + 该特性已经从 Web 标准中删除,虽然一些浏览器目前仍然支持它,但也许会在未来的某个时间停止支持,请尽量不要使用该特性。</p> +</div> + +<p><code><strong>anchor()</strong></code> 方法创建一个 {{HTMLElement("a")}} HTML 锚元素,被用作超文本靶标(hypertext target)。</p> + +<p id="Syntax">语法</p> + +<pre class="syntaxbox"><code>str.anchor(<em>name</em>) </code></pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>name</code></dt> + <dd>一个字符串,表示被创建的标签的 <code>name</code> 属性。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p> 包含 {{HTMLElement("a")}} HTML元素的一个字符串。</p> + +<h2 id="描述">描述</h2> + +<p>使用 <code>anchor</code> 方法能够以编程方式在一个文档中创建和展现一个锚链接。</p> + +<p>语法上来讲,字符串表示你想让用户看到的文本。<code>name</code> 字符串参数表示 {{HTMLElement("a")}} 元素的 <code>name</code> 属性。</p> + +<p>使用 anchor 方法创建的锚点(anchors)将会成为 {{domxref("document.anchors")}} 数组的元素。</p> + +<h2 id="示例">示例</h2> + +<h3 id="例子:使用_anchor">例子:使用 <code>anchor</code></h3> + +<pre class="brush:js">var myString = "Table of Contents"; + +document.body.innerHTML = myString.anchor("contents_anchor");</pre> + +<p>将会输出下面的 HTML:</p> + +<pre class="brush: html"><a name="contents_anchor">Table of Contents</a></pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">注释</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.anchor', 'String.prototype.anchor')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.<br> + Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatGeckoDesktop("1.0") }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatGeckoMobile("1.0") }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Gecko-specific_notes">Gecko-specific notes</h3> + +<p>从{{gecko("17")}}开始 <strong>"</strong> (引号) 被 HTML引用字符 <code>&quot所替代</code>;在字符串中申请<code>命名参数</code>.</p> + +<h2 id="See_Also" name="See_Also">相关链接</h2> + +<ul> + <li>{{jsxref("String.prototype.link()")}}</li> +</ul> 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 +--- +<div>{{JSRef}} {{deprecated_header}}</div> + +<p><strong><code>big()</code></strong>方法的作用是创建一个使字符串显示大号字体的{{HTMLElement("big")}}标签。</p> + +<div class="note"> +<p><strong>使用说明:</strong> <big> 元素在<a href="/en-US/docs/Web/Guide/HTML/HTML5">HTML5</a>中已经被移除了,不应该再使用它。 取而代之的是web开发人员应该使用<a href="/en-US/docs/Web/CSS">CSS</a> 属性。</p> +</div> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code><var>str</var>.big()</code></pre> + +<h3 id="返回值">返回值</h3> + +<p>带有 {{HTMLElement("big")}}标签的字符串。</p> + +<h2 id="描述">描述</h2> + +<p><code>big()</code> 方法会将一个字符串嵌入到<code><big>标签中:</code> <code>"<big>str</big>"。</code></p> + +<h2 id="示例">示例</h2> + +<h3 id="使用big()函数"><code><font face="Open Sans, Arial, sans-serif">使用</font>big()函数</code></h3> + +<p>下面的例子使用了字符串方法来改变一个字符串的字体大小:</p> + +<pre class="brush: js">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> +</pre> + +<p>使用 {{domxref("HTMLElement.style", "element.style")}} 对象,你能更加一般地获得和操作该元素的style属性,比如:</p> + +<pre class="brush: js">document.getElementById('yourElemId').style.fontSize = '2em'; +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.big', 'String.prototype.big')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>初始定义。 在JavaScript 1.0中实现。在(规范性)附件B中定义了用于Web浏览器的附加ECMAScript 特性。</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.big', 'String.prototype.big')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>在(规范性)附件B中定义了用于Web浏览器的附加ECMAScript 特性。</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("String.prototype.fontsize()")}}</li> + <li>{{jsxref("String.prototype.small()")}}</li> +</ul> 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 +--- +<div>{{JSRef}} {{deprecated_header}}</div> + +<p><strong><code>blink()</code></strong>方法创建使字符串闪烁的 {{HTMLElement("blink")}} HTML 元素。</p> + +<div class="warning"> +<p><strong>警告:</strong>闪烁文本被多种普及标准否决。 <code><blink></code>元素自身是非标准的,并且已废弃!</p> +</div> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code><var>str</var>.blink()</code></pre> + +<h3 id="返回值">返回值</h3> + +<p>包含 {{HTMLElement("blink")}} HTML 元素的字符串。</p> + +<h2 id="描述">描述</h2> + +<p><code>blink()</code>方法将字符串嵌入 <code><blink></code> 标签中: <code>"<blink>str</blink>"</code>.</p> + +<h2 id="示例">示例</h2> + +<h3 id="使用blink()函数"><code>使用blink()函数</code></h3> + +<p>下面的示例使用了字符串方法来修改字符串格式:</p> + +<pre class="brush: js">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></pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.blink', 'String.prototype.blink')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>初始定义。在 JavaScript 1.0 中实现。 在(规范性)附件 B 中定义了用于 Web 浏览器的 ECMAScript 附加特性。</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.blink', 'String.prototype.blink')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>在(规范性)附件 B 中定义了用于 Web 浏览器的 ECMAScript 附加特性。</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("String.prototype.bold()")}}</li> + <li>{{jsxref("String.prototype.italics()")}}</li> + <li>{{jsxref("String.prototype.strike()")}}</li> +</ul> 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 +--- +<p>{{JSRef}} {{deprecated_header}}</p> + +<p id="概述"><strong><code>bold() </code></strong><code>方法会创建</code> HTML 元素 “b”,并将字符串加粗展示。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code><var>str</var>.bold()</code></pre> + +<h3 id="返回值"><strong>返回值</strong></h3> + +<p>包含HTML元素 {{HTMLElement("b")}} 的字符串。</p> + +<h2 id="描述">描述</h2> + +<p><code>bold()</code> 方法将一个字符串嵌入到<b></b>标记中。</p> + +<h2 id="示例">示例</h2> + +<h3 id="使用bold()"><code><font face="Open Sans, Arial, sans-serif">使用</font>bold()</code></h3> + +<p>下面的例子使用字符串方法来改变字符串的格式。</p> + +<pre class="brush: js">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></pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.bold', 'String.prototype.bold')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0. Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.bold', 'String.prototype.bold')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="相关连接">相关连接</h2> + +<ul> + <li>{{jsxref("String.prototype.blink()")}}</li> + <li>{{jsxref("String.prototype.italics()")}}</li> + <li>{{jsxref("String.prototype.strike()")}}</li> +</ul> 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 +--- +<p>{{JSRef}}</p> + +<h2 id="Summary" name="Summary">概述</h2> + +<p><strong>charAt()</strong> 方法从一个字符串中返回指定的字符。</p> + +<h2 id="Syntax" name="Syntax">语法</h2> + +<pre class="syntaxbox"><em>str</em>.charAt(<em>index</em>)</pre> + +<h3 id="Parameters" name="Parameters">参数</h3> + +<dl> + <dt><code>index</code></dt> + <dd>一个介于0 和字符串长度减1之间的整数。 (0~length-1)</dd> + <dd>如果没有提供索引,charAt() 将使用0。</dd> + <dt> </dt> +</dl> + +<h2 id="Description" name="Description">描述</h2> + +<p>字符串中的字符从左向右索引,第一个字符的索引值为 0,最后一个字符(假设该字符位于字符串 stringName 中)的索引值为 <code>stringName.length - 1</code>。 如果指定的 index 值超出了该范围,则返回一个空字符串。</p> + +<h2 id="Examples" name="Examples">示例</h2> + +<h3 id="Example:_Displaying_characters_at_different_locations_in_a_string" name="Example:_Displaying_characters_at_different_locations_in_a_string">例子:输出字符串中不同位置的字符</h3> + +<p>下例输出字符串 "<code>Brave new world</code>" 不同位置处的字符:</p> + +<pre class="brush:js">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) + "'"); +</pre> + +<p>上面代码的输出为:</p> + +<pre>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 '' +</pre> + +<h3 id="例子:获取所有字符">例子:获取所有字符</h3> + +<p>以下提供了一种确保通过字符串循环总是提供整个字符的方法,即使该字符串包含不在<a href="https://zh.wikipedia.org/wiki/Unicode%E5%AD%97%E7%AC%A6%E5%B9%B3%E9%9D%A2%E6%98%A0%E5%B0%84#.E5.9F.BA.E6.9C.AC.E5.A4.9A.E6.96.87.E7.A7.8D.E5.B9.B3.E9.9D.A2">基本多文种平面</a>(BMP)中的字符。</p> + +<pre class="brush:js">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; +} + +</pre> + +<p>在允许解构分配的独占JavaScript 1.7+环境(如Firefox)中,以下是一个更简洁和更灵活的替代方法,它会自动递增一个递增变量(如果字符保证它是一个替代对)。</p> + +<pre class="brush: js">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]; +}</pre> + +<h3 id="示例:修复charAt以支持非基本多文种平面(BMP)字符">示例:修复charAt以支持非基本多文种平面(BMP)字符</h3> + +<p>虽然上面的例子对于那些希望支持非BMP字符的用户可能更有用(因为它不要求调用者知道任何非BMP字符可能出现在哪里),在人们希望的情况下,在选择字符 通过索引,将字符串中的替代对作为它们表示的单个字符,可以使用以下:</p> + +<pre class="brush: js">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; +}</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>ECMAScript 1st Edition.</td> + <td>Standard</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.4', 'String.prototype.charAt')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.charat', 'String.prototype.charAt')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also" name="See_also">相关链接</h2> + +<ul> + <li>{{jsxref("String.prototype.indexOf()")}}, {{jsxref("String.prototype.lastIndexOf()")}}</li> + <li>{{jsxref("String.prototype.split()")}}</li> + <li>{{jsxref("String.prototype.charCodeAt()")}}</li> + <li>{{jsxref("String.fromCodePoint()")}}</li> + <li>{{jsxref("String.prototype.codePointAt()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><code><strong>charCodeAt()</strong></code> 方法返回 <code>0</code> 到 <code>65535</code> 之间的整数,表示给定索引处的 UTF-16 代码单元</p> + +<div>{{EmbedInteractiveExample("pages/js/string-charcodeat.html", "shorter")}}</div> + + + +<p>UTF-16 编码单元匹配能用一个 UTF-16 编码单元表示的 Unicode 码点。如果 Unicode 码点不能用一个 UTF-16 编码单元表示(因为它的值大于<code>0xFFFF</code>),则所返回的编码单元会是这个码点代理对的第一个编码单元) 。如果你想要整个码点的值,使用 {{jsxref("Global_Objects/String/codePointAt", "codePointAt()")}}。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox notranslate"><code><em>str</em>.charCodeAt(<em>index</em>)</code></pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>index</code></dt> + <dd>一个大于等于 <code>0</code>,小于字符串长度的整数。如果不是一个数值,则默认为 <code>0</code>。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>指定 <code>index</code> 处字符的 UTF-16 代码单元值的一个数字;如果 <code>index</code> 超出范围,<code>charCodeAt()</code> 返回 {{jsxref("Global_Objects/NaN", "NaN")}}。</p> + +<h2 id="描述">描述</h2> + +<p>Unicode 码点(code points)的范围从 <code>0</code> 到 <code>1114111</code> <code>(0x10FFFF)</code>。开头的 128 个 Unicode 编码单元和 ASCII 字符编码一样。(关于 Unicode 的更多信息,可查看 <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Unicode">JavaScript Guide</a>。)</p> + +<div class="blockIndicator note"> +<p><strong>注意:</strong>,<code>charCodeAt</code> 总是返回一个小于 65,536 的值。这是因为高位编码单元(higher code point)使用一对(低位编码 lower valued)代理伪字符("surrogate" pseudo-characters)来表示,从而构成一个真正的字符。</p> + +<p>因此,为了检查(或重现)<code>65536</code> 及以上编码字符的完整字符,需要在获取 <code>charCodeAt(i)</code> 的值的同时获取 <code>charCodeAt(i+1)</code> 的值(如同用两个字母操纵一个字符串),或者改为获取 <code>codePointAt(i)</code> 的值。参看下面例 2 和例 3。</p> +</div> + +<p>如果指定的 <code>index</code> 小于 <code>0</code> 、等于或大于字符串的长度,则 <code>charCodeAt</code> 返回 {{jsxref("Global_Objects/NaN", "NaN")}}。</p> + +<p>向后兼容:在历史版本中(如 JavaScript 1.2),<code>charCodeAt</code> 返回一个数字,表示给定 index 处字符的 ISO-Latin-1 编码值。ISO-Latin-1 编码集范围从 <code>0</code> 到 <code>255</code>。开头的 <code>0</code> 到 <code>127</code> 直接匹配 ASCII 字符集。</p> + +<h2 id="Examples" name="Examples">示例</h2> + +<h3 id="Example_Using_charCodeAt" name="Example:_Using_charCodeAt">使用 <code>charCodeAt()</code></h3> + +<p>下例介绍了不同索引情况下返回的 Unicode 值:</p> + +<pre class="brush: js notranslate">"ABC".charCodeAt(0) // returns 65:"A" + +"ABC".charCodeAt(1) // returns 66:"B" + +"ABC".charCodeAt(2) // returns 67:"C" + +"ABC".charCodeAt(3) // returns NaN</pre> + +<h3 id="使用_charCodeAt_修复字符串中出现的未知的非基本多语言范围(非BMP,non-Basic-Multilingual-Plane)字符">使用 <code>charCodeAt()</code> 修复字符串中出现的未知的非基本多语言范围(非BMP,non-Basic-Multilingual-Plane)字符</h3> + +<p>这段代码可以被用在 for 循环和其他类似语句中,当在指定引索之前不确定是否有非BMP字符存在时。</p> + +<pre class="brush:js notranslate">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; +} +</pre> + +<h3 id="使用_charCodeAt_修复字符串中出现的已知的非BMP字符">使用 <code>charCodeAt()</code> 修复字符串中出现的已知的非BMP字符</h3> + +<pre class="brush:js notranslate">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; +} + +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.charcodeat', 'String.prototype.charCodeAt')}}</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.charCodeAt")}}</p> + +<h2 id="参见">参见</h2> + +<ul> + <li>{{jsxref("String.fromCharCode()")}}</li> + <li>{{jsxref("String.prototype.charAt()")}}</li> + <li>{{jsxref("String.fromCodePoint()")}}</li> + <li>{{jsxref("String.prototype.codePointAt()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><strong><code>codePointAt()</code></strong> 方法返回 一个 Unicode 编码点值的非负整数。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code><var>str</var>.codePointAt(<var>pos</var>)</code></pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>pos</code></dt> + <dd>这个字符串中需要转码的元素的位置。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>返回值是在字符串中的给定索引的编码单元体现的数字,如果在索引处没找到元素则返回 {{jsxref("undefined")}} 。</p> + +<h2 id="描述">描述</h2> + +<p>如果在指定的位置没有元素则返回 {{jsxref("undefined")}} 。如果在索引处开始没有UTF-16 代理对,将直接返回在那个索引处的编码单元。</p> + +<p>Surrogate Pair是UTF-16中用于扩展字符而使用的编码方式,是一种采用四个字节(两个UTF-16编码)来表示一个字符,称作代理对。</p> + +<h2 id="例子">例子</h2> + +<h3 id="使用_codePointAt()">使用 <code>codePointAt()</code></h3> + +<pre class="brush: js">'ABC'.codePointAt(1); // 66 +'\uD800\uDC00'.codePointAt(0); // 65536 + +'XYZ'.codePointAt(42); // undefined +</pre> + +<h2 id="替补支持(Polyfill)">替补支持(Polyfill)</h2> + +<p>给原生不支持 ECMAScript 6 的浏览器使用<code>codePointAt()</code>方法的的一个字符串扩展方法。</p> + +<pre class="brush: js">/*! 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; + } + }()); +} +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.codepointat', 'String.prototype.codePointAt')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.codepointat', 'String.prototype.codePointAt')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>特性</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>基本支持</td> + <td>{{CompatChrome("41")}}</td> + <td>{{CompatGeckoDesktop("29")}}</td> + <td>11</td> + <td>{{CompatOpera("28")}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>特性</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>基本支持</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile("29")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("String.fromCodePoint()")}}</li> + <li>{{jsxref("String.fromCharCode()")}}</li> + <li>{{jsxref("String.prototype.charCodeAt()")}}</li> + <li>{{jsxref("String.prototype.charAt()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><strong><code>concat()</code></strong> 方法将一个或多个字符串与原字符串连接合并,形成一个新的字符串并返回。</p> + +<h2 id="Syntax" name="Syntax">语法</h2> + +<pre class="notranslate"><code><var>str</var>.concat(<var>str2</var>, [, ...<var>strN</var>])</code></pre> + +<h3 id="Parameters" name="Parameters">参数</h3> + +<dl> + <dt><code><var>str2</var> [, ...<var>strN</var>]</code></dt> + <dd>需要连接到 <code><var>str</var></code> 的字符串。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>一个新的字符串,包含参数所提供的连接字符串。</p> + +<h2 id="Description" name="Description">描述</h2> + +<p><code>concat</code> 方法将一个或多个字符串与原字符串连接合并,形成一个新的字符串并返回。 <code>concat</code> 方法并不影响原字符串。</p> + +<p>如果参数不是字符串类型,它们在连接之前将会被转换成字符串。</p> + +<h2 id="性能" style="margin-bottom: 20px; line-height: 30px;">性能</h2> + +<p>强烈建议使用<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Assignment_Operators">赋值操作符</a>(<code>+</code>, <code>+=</code>)代替 <code>concat</code> 方法。</p> + +<h2 id="Examples" name="Examples">示例</h2> + +<h3 id="Examples" name="Examples">使用 <code>concat</code></h3> + +<p>下面的例子演示如何将多个字符串与原字符串合并为一个新字符串</p> + +<pre class="brush: js notranslate">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"</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.concat', 'String.prototype.concat')}}</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{Compat("javascript.builtins.String.concat")}}</p> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("Array.prototype.concat()")}}</li> + <li>{{jsxref("Operators/Assignment_Operators", "Assignment operators", "", 1)}}</li> +</ul> 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 +--- +<p>{{JSRef}}</p> + +<p><code><strong>endsWith()</strong></code>方法用来判断当前字符串是否是以另外一个给定的子字符串“结尾”的,根据判断结果返回 <code>true</code> 或 <code>false</code>。</p> + +<div>{{EmbedInteractiveExample("pages/js/string-endswith.html")}}</div> + + + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox notranslate"><var>str</var>.endsWith(<var>searchString</var>[, <var>length</var>])</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>searchString</code></dt> + <dd>要搜索的子字符串。</dd> + <dt><code><var>length</var></code> {{optional_inline}}</dt> + <dd>作为 <code>str</code> 的长度。默认值为 <code>str.length</code>。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>如果传入的子字符串在搜索字符串的末尾则返回<strong><code>true</code></strong>;否则将返回 <strong><code>false</code></strong>。</p> + +<h2 id="描述">描述</h2> + +<p>这个方法帮助你确定一个字符串是否在另一个字符串的末尾。这个方法是大小写敏感的。</p> + +<h2 id="Polyfill">Polyfill</h2> + +<p>这个方法已经加入到 ECMAScript 6 标准当中,但是可能还没有在所有的 JavaScript 实现中可用。然而,你可以通过如下的代码片段扩展 <code>String.prototype.endsWith()</code> 实现兼容:</p> + +<pre class="brush: js notranslate">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; + }; +} +</pre> + +<h2 id="示例">示例</h2> + +<h3 id="使用_endsWith">使用 <code>endsWith()</code></h3> + +<pre class="brush:js; notranslate">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 +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.endswith', 'String.prototype.endsWith')}}</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div class="hidden"> +<p>这个页面上的兼容性表格是通过结构化的数据自动生成的,如果你希望改进这些数据,你可以查看 <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> 并提交你的改进。 </p> +</div> + +<p>{{Compat("javascript.builtins.String.endsWith")}}</p> + +<h2 id="参见">参见</h2> + +<ul> + <li>{{jsxref("String.prototype.startsWith()")}}</li> + <li>{{jsxref("String.prototype.includes()")}}</li> + <li>{{jsxref("String.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> +</ul> 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 +--- +<div>{{JSRef}} {{deprecated_header}}</div> + +<p>fixed()方法创建了一个<tt>标签元素将字符串包裹起来,从而让这个字符串里面的内容具有固定间距。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox">str.fixed() +</pre> + +<h3 id="Return_value">Return value</h3> + +<p>返回一个表示 {{HTMLElement("tt")}} HTML 元素的字符串。</p> + +<h2 id="描述">描述</h2> + +<p id="fixed()_方法将一个字符串包裹在<tt><tt>标签中,比如_<tt>str<tt>."><code style="font-size: 14px; font-style: normal; font-weight: normal; line-height: 1.5;">fixed()</code><span style="font-size: 14px; font-weight: normal; line-height: 1.5;"> 方法将一个字符串包裹在<tt></tt>标签中,比如</span><span style="font-size: 14px; font-weight: normal; line-height: 1.5;">: </span><code style="font-size: 14px; font-style: normal; font-weight: normal; line-height: 1.5;">"<tt>str</tt>"</code><span style="font-size: 14px; font-weight: normal; line-height: 1.5;">.</span></p> + +<h2 id="举例">举例</h2> + +<h3 id="使用fixed()">使用fixed()</h3> + +<p>下面的示例代码使用这个fixed方法来改变字符串的格式:</p> + +<pre class="brush: js">var worldString = 'Hello, world'; +console.log(worldString.fixed()); // "<tt>Hello, world</tt>" +</pre> + +<h2 id="说明">说明</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.fixed', 'String.prototype.fixed')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0. Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.fixed', 'String.prototype.fixed')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>版本</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>版本</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("String.prototype.bold()")}}</li> + <li>{{jsxref("String.prototype.italics()")}}</li> + <li>{{jsxref("String.prototype.strike()")}}</li> +</ul> 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 +--- +<div><font><font>{{JSRef}} {{deprecated_header}}</font></font></div> + +<p><strong><code>fontcolor()</code></strong><font><font>方法创建一个{{HTMLElement("font")}}的HTML元素让字符串被显示成指定的字体颜色。</font></font></p> + +<div class="note"> +<p><strong><font><font>使用注意:</font></font></strong><font><font><font>元素已经在在</font></font><a href="/en-US/docs/Web/Guide/HTML/HTML5"><font><font>HTML5中</font></font></a><font><font>被移除并且不应该在使用。</font><font>替代的是,web开发者应该使用</font></font><a href="/en-US/docs/Web/CSS"><font><font>CSS</font></font></a><font><font>属性。</font></font></p> +</div> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code><var>str</var>.fontcolor(<var>color</var>)</code></pre> + +<h3 id="参数"><font><font>参数</font></font></h3> + +<dl> + <dt><code>color</code></dt> + <dd><font><font>代表颜色的一个字符串,可以是三个一组的十六进制的RGB值,也可以是一个颜色名称的字符串字面量,</font><font>颜色名称的字符串字面量被列在了这里</font></font><a href="/en-US/docs/Web/CSS/color_value"><font><font>CSS颜色参考</font></font></a><font><font>。</font></font></dd> +</dl> + +<h3 id="返回值"><font><font>返回值</font></font></h3> + +<dl> + <dd><font><font>一个包含一个{{HTMLElement("font")}} HTML元素的字符串。</font></font></dd> +</dl> + +<h2 id="描述"><font><font>描述</font></font></h2> + +<p><font><font>如果你表示的颜色为十六进制RGB三原色,则必须使用的格式</font></font><code>rrggbb</code><font><font>。</font><font>例如,对于橙红色的十六进制RGB值是红色=FA,绿色=80,和蓝=72,所以橙红色的RGB三原色</font></font><code>"FA8072"</code><font><font>。</font></font></p> + +<h2 id="例子"><font><font>例子</font></font></h2> + +<h3 id="使用_fontcolor()"><font><font>使用 </font></font><code>fontcolor()</code></h3> + +<p><font><font>下面的示例使用</font></font><code>fontcolor()</code><font><font>方法来改变字符串的颜色,通过产生一个被HTML <font> 标签包裹的字符串</font></font>。</p> + +<pre class="brush: js"><font><font>var worldString = "Hello, world"</font></font> +<font><font> +console.log(worldString.fontcolor('red') + ' is red in this line'); +// <font color="red">Hello, world </font> is red in this line"</font></font> +<font><font> +console.log(worldString.fontcolor('FF00') + ' is red in hexadecimal'</font></font><font><font> +// <font color="FF00">Hello,world </font> is red in hexadecimal</font></font> +</pre> + +<p><font><font>和{{domxref("HTMLElement.style","element.style")}}对象一起,你可以访问元素的</font></font><code>style</code><font><font>属性,并且更随意的去操纵它,例如:</font></font></p> + +<pre class="brush: js"><font><font>document.getElementById('yourElemId').style.color ='red'; +</font></font></pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col"><font><font>规范</font></font></th> + <th scope="col"><font><font>状态</font></font></th> + <th scope="col"><font><font>评论</font></font></th> + </tr> + <tr> + <td><font><font>{{SpecName('ES6','#string.prototype.fontcolor', 'String.prototype.fontcolor')}}</font></font></td> + <td><font><font>{{Spec2('ES6')}}</font></font></td> + <td><font><font>初始定义。</font><font>实现在JavaScript中1.0。</font><font>定义为附加功能的ECMAScript针对Web浏览器(规范)附件B。</font></font></td> + </tr> + <tr> + <td><font><font>{{SpecName('ESDraft', '#string.prototype.fontcolor', 'String.prototype.fontcolor')}}</font></font></td> + <td><font><font>{{Spec2('ESDraft')}}</font></font></td> + <td><font><font>定义为附加功能的ECMAScript针对Web浏览器(规范)附件B。</font></font></td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性"><font><font>浏览器兼容性</font></font></h2> + +<div><font><font>{{CompatibilityTable}}</font></font></div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th><font><font>Firefox(Gecko)</font></font></th> + <th>Internet Explorer</th> + <th>Opera</th> + <th><font><font>Safari</font></font></th> + </tr> + <tr> + <td>Basic Support</td> + <td><font><font>{{CompatVersionUnknown}}</font></font></td> + <td><font><font>{{CompatGeckoDesktop("1.0")}}</font></font></td> + <td><font><font>{{CompatVersionUnknown}}</font></font></td> + <td><font><font>{{CompatVersionUnknown}}</font></font></td> + <td><font><font>{{CompatVersionUnknown}}</font></font></td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th><font><font>Android</font></font></th> + <th><font><font>Chrome for Android</font></font></th> + <th><font><font>Firefox Mobile(Gecko)</font></font></th> + <th><font><font>IE Mobile</font></font></th> + <th><font><font>Opera Mobile</font></font></th> + <th><font><font>Safari Mobile</font></font></th> + </tr> + <tr> + <td>Basic Support</td> + <td><font><font>{{CompatVersionUnknown}}</font></font></td> + <td><font><font>{{CompatVersionUnknown}}</font></font></td> + <td><font><font>{{CompatGeckoMobile("1.0")}}</font></font></td> + <td><font><font>{{CompatVersionUnknown}}</font></font></td> + <td><font><font>{{CompatVersionUnknown}}</font></font></td> + <td><font><font>{{CompatVersionUnknown}}</font></font></td> + </tr> + </tbody> +</table> +</div> + +<h2 id="也可以看看"><font><font>也可以看看</font></font></h2> + +<ul> + <li><font><font>{{jsxref("String.prototype.fontsize()")}}</font></font></li> +</ul> 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 +--- +<div>{{JSRef}} {{deprecated_header}}</div> + +<p>The <strong><code>fontsize()</code></strong> method creates a {{HTMLElement("font")}} HTML element that causes a string to be displayed in the specified font size.</p> + +<div class="note"> +<p><strong>Usage note:</strong> The <font> element has been removed in <a href="/en-US/docs/Web/Guide/HTML/HTML5">HTML5</a> and shouldn't be used anymore. Instead web developers should use <a href="/en-US/docs/Web/CSS">CSS</a> properties.</p> +</div> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code><var>str</var>.fontsize(<var>size</var>)</code></pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>size</code></dt> + <dd>An integer between 1 and 7, a string representing a signed integer between 1 and 7.</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>A string containing a {{HTMLElement("font")}} HTML element.</p> + +<h2 id="描述">描述</h2> + +<p>When you specify size as an integer, you set the font size of <code>str</code> to one of the 7 defined sizes. When you specify <code>size</code> as a string such as "-2", you adjust the font size of <code>str</code> relative to the size set in the {{HTMLElement("basefont")}} tag.</p> + +<h2 id="示例">示例</h2> + +<h3 id="使用fontsize()方法"><code><font face="Open Sans, Arial, sans-serif">使用</font>fontsize()方法</code></h3> + +<p>The following example uses string methods to change the size of a string:</p> + +<pre class="brush: js">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> +</pre> + +<p>With the {{domxref("HTMLElement.style", "element.style")}} object you can get the element's <code>style</code> attribute and manipulate it more generically, for example:</p> + +<pre class="brush: js">document.getElementById('yourElemId').style.fontSize = '0.7em'; +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.fontsize', 'String.prototype.fontsize')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0. Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.fontsize', 'String.prototype.fontsize')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("String.prototype.big()")}}</li> + <li>{{jsxref("String.prototype.small()")}}</li> +</ul> 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 +--- +<p>{{JSRef}}</p> + +<p>静态 <strong><code>String.fromCharCode()</code></strong> 方法返回由指定的 UTF-16 代码单元序列创建的字符串。</p> + +<div>{{EmbedInteractiveExample("pages/js/string-fromcharcode.html")}}</div> + + + +<h2 id="Syntax" name="Syntax">语法</h2> + +<pre class="syntaxbox notranslate"><code>String.fromCharCode(<var>num1</var>[, ...[, <var>numN</var>]])</code></pre> + +<h3 id="Parameters" name="Parameters">参数</h3> + +<dl> + <dt><code>num1, ..., num<em>N</em></code></dt> + <dd>一系列 UTF-16 代码单元的数字。范围介于 <code>0</code> 到 <code>65535</code>(<code>0xFFFF</code>)之间。大于 <code>0xFFFF</code> 的数字将被截断。不进行有效性检查。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>一个长度为 <code>N</code> 的字符串,由 <code>N</code> 个指定的 UTF-16 代码单元组成。</p> + +<h2 id="Description" name="Description">描述</h2> + +<p>该方法返回一个字符串,而不是一个 {{jsxref("String")}} 对象。</p> + +<p>由于 <code>fromCharCode()</code> 是 {{jsxref("String")}} 的静态方法,所以应该像这样使用:<code>String.fromCharCode()</code>,而不是作为你创建的 {{jsxref("String")}} 对象的方法。</p> + +<h3 id="返回补充字符">返回补充字符</h3> + +<p>在 UTF-16 中,绝大部分常用的字符可以用一个 16 位的值表示(即一个代码单元)。然而,有一类字符叫 Base Multilingual Plane (BMP),是所有可寻址的 Unicode 码点的 <sup>1</sup>/<sub>17</sub><sup>th</sup>。剩下的码点,从范围 <code>65536</code> (<code>0x010000</code>) 到 <code>1114111</code> (<code>0x10FFFF</code>) 被称之为补充字符。在 UTF-16 中,补充字符也叫代理(surrogates),用两个 16 位代码单元表示,它是有目的被保留下来的。两个代理(surrogates)形成一个有效组合,也叫代理对,可以用来表示一个补充字符。</p> + +<p>因为 <code>fromCharCode()</code> 只作用于 16 位的值 (跟 <code>\u</code> 转义序列一样),为了返回一个补充字符,一个代理对是必须的。例如,<code>String.fromCharCode(0xD83C, 0xDF03)</code> 和 <code>\uD83C\uDF03</code> 返回码点 <code>U+1F303</code> "Night with Stars"。</p> + +<p>While there is a mathematical relationship between the supplementary code point value (e.g. <code>0x1F303</code>) and both surrogate values that represent it (e.g., <code>0xD83C</code> and <code>0xDF03</code>), 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 标准下的一个方法)更方便, 这个方法允许你基于真实的码点返回补充字符。例如 <code>String.fromCodePoint(0x1F303)</code> 返回码点 <code>U+1F303</code> "Night with Stars"。</p> + +<h2 id="示例">示例</h2> + +<h3 id="使用_fromCharCode">使用 <code>fromCharCode()</code></h3> + +<p>在 UTF-16 中,BMP 字符使用一个代码单元:</p> + +<pre class="brush: js notranslate">String.fromCharCode(65, 66, 67); // 返回 "ABC" +String.fromCharCode(0x2014); // 返回 "—" +String.fromCharCode(0x12014); // 也是返回 "—"; 数字 1 被剔除并忽略 +String.fromCharCode(8212); // 也是返回 "—"; 8212 是 0x2014 的十进制表示 +</pre> + +<p><a href="https://asecuritysite.com/coding/asc2">完整的 UTF 16 表格</a>.<br> + 在 UTF-16 中,补充字符需要两个代码单元(即一个代理对):</p> + +<pre class="brush: js notranslate">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" +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.fromcharcode', 'String.fromCharCode')}}</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{Compat("javascript.builtins.String.fromCharCode")}}</p> + +<h2 id="See_also" name="See_also">相关链接</h2> + +<ul> + <li>{{jsxref("String.prototype.charCodeAt()")}}</li> + <li>{{jsxref("String.prototype.charAt()")}}</li> + <li>{{jsxref("String.fromCodePoint()")}}</li> + <li>{{jsxref("String.prototype.codePointAt()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><strong><code>String.fromCodePoint()</code> 静态方法返回使用指定的代码点序列创建的字符串。</strong></p> + +<div>{{EmbedInteractiveExample("pages/js/string-fromcodepoint.html")}}</div> + + + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code>String.fromCodePoint(<var>num1</var>[, ...[, <var>numN</var>]])</code></pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>num1, ..., num<em>N</em></code></dt> + <dd>一串 Unicode 编码位置,即“代码点”。</dd> + <dt> + <h3 id="返回值">返回值</h3> + + <p>使用指定的 Unicode 编码位置创建的字符串。</p> + </dt> +</dl> + +<h3 id="异常">异常</h3> + +<dl> + <dt>{{jsxref("RangeError")}}</dt> + <dd>如果传入无效的 Unicode 编码,将会抛出一个{{jsxref("RangeError")}} (例如: "RangeError: NaN is not a valid code point")。</dd> +</dl> + +<h2 id="说明">说明</h2> + +<p>该方法返回一个字符串,而不是一个 {{jsxref("String")}} 对象。</p> + +<p>因为 <code>fromCodePoint()</code> 是 {{jsxref("String")}} 的一个静态方法,所以只能通过 <code>String.fromCodePoint()</code> 这样的方式来使用,不能在你创建的 {{jsxref("String")}} 对象实例上直接调用。</p> + +<h2 id="例子">例子</h2> + +<h3 id="使用_fromCodePoint()">使用 <code>fromCodePoint()</code></h3> + +<pre class="brush: js">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 +</pre> + +<pre class="brush: js">// String.fromCharCode() 方法不能单独获取在高代码点位上的字符 +// 另一方面,下列的示例中,可以返回 4 字节,也可以返回 2 字节的字符 +// (也就是说,它可以返回单独的字符,使用长度 2 代替 1!) +console.log(String.fromCodePoint(0x2F804)); // or 194564 in decimal +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>String.fromCodePoint</code> 方法是 ECMAScript2015(ES6)新增加的特性,所以一些老的浏览器可能还不支持。可以通过使用下面的 polyfill 代码来保证浏览器的支持:</p> + +<pre class="brush: js">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)); +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-string.fromcodepoint', 'String.fromCodePoint')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.fromcodepoint', 'String.fromCodePoint')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.fromCodePoint")}}</p> + +<h2 id="参见">参见</h2> + +<ul> + <li>{{jsxref("String.fromCharCode()")}}</li> + <li>{{jsxref("String.prototype.charAt()")}}</li> + <li>{{jsxref("String.prototype.codePointAt()")}}</li> + <li>{{jsxref("String.prototype.charCodeAt()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><strong><code>includes()</code> </strong>方法用于判断一个字符串是否包含在另一个字符串中,根据情况返回 true 或 false。</p> + +<h2 id="Syntax" name="Syntax">语法</h2> + +<pre class="syntaxbox notranslate"><var>str</var>.includes(<var>searchString</var>[, <var>position</var>])</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>searchString</code></dt> + <dd>要在此字符串中搜索的字符串。</dd> + <dt><code><var>position</var></code> {{optional_inline}}</dt> + <dd>从当前字符串的哪个索引位置开始搜寻子字符串,默认值为 <code>0</code>。</dd> + <dt> + <h3 id="返回值">返回值</h3> + </dt> + <dd>如果当前字符串包含被搜寻的字符串,就返回 <strong><code>true</code></strong>;否则返回 <strong><code>false</code></strong>。</dd> +</dl> + +<h2 id="描述">描述</h2> + +<p>这个方法可以帮你判断一个字符串是否包含另外一个字符串。</p> + +<h3 id="区分大小写">区分大小写</h3> + +<p><code>includes()</code> 方法是区分大小写的。例如,下面的表达式会返回 <strong><code>false</code></strong> :</p> + +<pre class="notranslate"><code>'Blue Whale'.includes('blue'); // returns false</code></pre> + +<h2 id="兼容补丁">兼容补丁</h2> + +<p>这个方法已经被加入到 ECMAScript 6 标准中,但未必在所有的 JavaScript 实现中都可以使用。然而,你可以轻松地 polyfill 这个方法:</p> + +<pre class="notranslate"><code>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; + } + }; +}</code></pre> + +<h2 id="Examples" name="Examples">示例</h2> + +<h3 id="使用_includes">使用 includes()</h3> + +<pre class="notranslate"><code>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</code></pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.includes', 'String.prototype.includes')}}</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{Compat("javascript.builtins.String.includes")}}</p> + +<h2 id="String.prototype.contains">String.prototype.contains()</h2> + +<p>在 Firefox 18 - 39中,这个方法的名称叫 <code>contains()</code>。由于下面的理由,在{{bug(1102219)}}中,它被重命名为 <code>includes()</code> :</p> + +<p>据报道,在Firefox 17上,一些使用 <a href="http://mootools.net/">MooTools</a> 1.2的网站会崩溃掉。这个版本的MooTools会检查函数 <code>String.prototype.contains()</code> 是否存在,如果不存在的话,MooTools就添加它自己的函数。通过在Firefox 17中引入这个函数,检查更改的行为在一定程度上导致了基于MooTools的 <code>String.prototype.contains() </code>函数的代码实现中断。结果是,当 <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=789036#c32">MooTools的拓展</a> 导致 <a href="http://mootools.net/blog/2013/02/19/mootools-1-2-6-released">MooTools 1.2.6</a> 版本的发布,此实现在Firefox 17中不可用和 <code>String.prototype.contains()</code> 在随后一个版本Firefox 18上是可用的。</p> + +<p>MooTools 1.3会强制使用它自己版本的函数 <code>String.prototype.contains()</code>,因此,依赖它的网站不会崩溃掉。然而,你应该注意此方法在 <a href="http://mootools.net/core/docs/1.3.2/Types/String#String-method:-contains">MooTools 1.3 </a>签名和ECMAScript 6 签名中的不同(在第二个参数)。后来,<a href="https://github.com/mootools/mootools-core/blob/master/Docs/Types/String.md#note">为了与ES6标准一致在MooTools 1.5版本及以上更改了签名</a>。</p> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("Array.prototype.includes()")}} {{experimental_inline}}</li> + <li>{{jsxref("TypedArray.prototype.includes()")}} {{experimental_inline}}</li> + <li>{{jsxref("String.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> + <li>{{jsxref("String.prototype.startsWith()")}}</li> + <li>{{jsxref("String.prototype.endsWith()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><strong><code>String</code></strong> 全局对象是一个用于字符串或一个字符序列的构造函数。</p> + +<h2 id="Syntax" name="Syntax">语法</h2> + +<p>字符串字面量采取以下形式:</p> + +<pre class="syntaxbox">'string text' +"string text" +"中文/汉语" +"español" +"English " +"हिन्दी" +"العربية" +"português" +"বাংলা" +"русский" +"日本語" +"ਪੰਜਾਬੀ" +"한국어"</pre> + +<p>你也能使用 <code>String</code> 函数将其他值生成或转换成字符串:</p> + +<pre class="syntaxbox">String(thing) +new String(thing)</pre> + +<h3 id="Parameters" name="Parameters">参数</h3> + +<dl> + <dt><code>thing</code></dt> + <dd>任何可以被转换成字符串的值。</dd> +</dl> + +<h3 id="Parameters" name="Parameters">模板字面量</h3> + +<p>从 ECMAScript 2015 开始,字符串字面量也可以称为<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals">模板字面量</a>:</p> + +<pre>`hello world` `hello! world!` `hello ${who}` escape `<a>${who}</a>`</pre> + +<h3 id="Parameters" name="Parameters">转义字符</h3> + +<dl> +</dl> + +<p>除了普通的可打印字符以外,一些有特殊功能的字符可以通过转义字符的形式放入字符串中:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Code</th> + <th scope="col">Output</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>\0</code></td> + <td>空字符</td> + </tr> + <tr> + <td><code>\'</code></td> + <td>单引号</td> + </tr> + <tr> + <td><code>\"</code></td> + <td><code>双引号</code></td> + </tr> + <tr> + <td><code>\\</code></td> + <td>反斜杠</td> + </tr> + <tr> + <td><code>\n</code></td> + <td>换行</td> + </tr> + <tr> + <td><code>\r</code></td> + <td><code>回车</code></td> + </tr> + <tr> + <td><code>\v</code></td> + <td>垂直制表符</td> + </tr> + <tr> + <td><code>\t</code></td> + <td>水平制表符</td> + </tr> + <tr> + <td><code>\b</code></td> + <td>退格</td> + </tr> + <tr> + <td><code>\f</code></td> + <td>换页</td> + </tr> + <tr> + <td><code>\uXXXX</code></td> + <td>unicode 码</td> + </tr> + <tr> + <td><code>\u{X}</code> ... <code>\u{XXXXXX}</code></td> + <td>unicode codepoint {{experimental_inline}}</td> + </tr> + <tr> + <td><code>\xXX</code></td> + <td>Latin-1 字符(x小写)</td> + </tr> + </tbody> +</table> + +<div class="note">和其他语言不同,javascript 的字符串不区分单引号和双引号,所以不论是单引号还是双引号的字符串,上面的转义字符都能运行 。</div> + +<h3 id="长字符串">长字符串</h3> + +<p>有时,你的代码可能含有很长的字符串。你可能想将这样的字符串写成多行,而不是让这一行无限延长或着被编辑器折叠。有两种方法可以做到这一点。</p> + +<p>其一,可以使用 + 运算符将多个字符串连接起来,如下所示:</p> + +<pre><code>let longString = "This is a very long string which needs " + + "to wrap across multiple lines because " + + "otherwise my code is unreadable.";</code></pre> + +<p>其二,可以在每行末尾使用反斜杠字符(“\”),以指示字符串将在下一行继续。确保反斜杠后面没有空格或任何除换行符之外的字符或缩进; 否则反斜杠将不会工作。 如下所示:</p> + +<pre><code>let longString = "This is a very long string which needs \ +to wrap across multiple lines because \ +otherwise my code is unreadable.";</code></pre> + +<p>使用这两种方式会创建相同的字符串。</p> + +<dl> +</dl> + +<h2 id="Description" name="Description">描述</h2> + +<p>字符串对于保存可以以文本形式表示的数据非常有用。 一些常用的字符串操作有:查询<a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/length">字符串长度</a>,使用<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/String_Operators"> + 和 += </a>运算符来构建和连接字符串,使用 <a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf">indexOf</a> 方法检查某一子字符串在父字符串中的位置,又或是使用 <a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/substring">substring</a> 方法提取从父字符串中提取子字符串。</p> + +<h3 id="Character_access" name="Character_access">从字符串中获取单个字符</h3> + +<p>获取字符串的某个字符有两种方法。 第一种是使用 {{jsxref("String.charAt", "charAt")}} 方法:</p> + +<pre class="brush: js">return 'cat'.charAt(1); // returns "a" +</pre> + +<p>另一种 (在ECMAScript 5中有所介绍) 是把字符串当作一个类似数组的对象,其中的每个字符对应一个数值索引:</p> + +<pre class="brush: js">return 'cat'[1]; // returns "a" +</pre> + +<p>使用括号访问字符串不可以对其进行删除或添加,因为字符串对应未知的属性并不是可读或配置的。 (更多的信息请参阅 {{jsxref("Object.defineProperty")}}。 )</p> + +<h3 id="Comparing_strings" name="Comparing_strings">字符串比较</h3> + +<p>熟练使用 C 语言的开发者经常使用 <code>strcmp</code> 函数来比较字符串,但在 JavaScript 中,你只需要使用<a href="/zh-CN/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">比较操作符(>/</>=/<=)</a>:</p> + +<pre class="brush: js">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."); +</pre> + +<p>使用从字符串实例继承而来的 {{jsxref("String.localeCompare", "localeCompare")}} 方法也能达到同样的效果。 </p> + +<h3 id="基本字符串和字符串对象的区别">基本字符串和<font face="Consolas, Liberation Mono, Courier, monospace">字符串</font>对象的区别</h3> + +<p>请注意区分 JavaScript 字符串对象和基本字符串值 . ( 对于 {{jsxref("Global_Objects/Boolean", "Boolean")}} 和{{jsxref("Global_Objects/Number", "Numbers")}} 也同样如此.)</p> + +<p>字符串字面量 (通过单引号或双引号定义) 和 直接调用 String 方法(没有通过 new 生成字符串对象实例)的字符串都是基本字符串。JavaScript会自动将基本字符串转换为字符串对象,只有将基本字符串转化为字符串对象之后才可以使用字符串对象的方法。当基本字符串需要调用一个字符串对象才有的方法或者查询值的时候(基本字符串是没有这些方法的),JavaScript 会自动将基本字符串转化为字符串对象并且调用相应的方法或者执行查询。</p> + +<pre class="brush: js">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" +</pre> + +<p>当使用 {{jsxref("Global_Objects/eval", "eval")}}时,基本字符串和<font face="Consolas, Liberation Mono, Courier, monospace">字符串</font>对象也会产生不同的结果。<code>eval</code> 会将基本字符串作为源代码处理; 而<font face="Consolas, Liberation Mono, Courier, monospace">字符串</font>对象则被看作对象处理, 返回对象。 例如:</p> + +<pre class="brush: js">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" +</pre> + +<p>由于上述原因, 当一段代码在需要使用基本字符串的时候却使用了字符串对象就会导致执行失败(虽然一般情况下程序员们并不需要考虑这样的问题)。</p> + +<p>利用 {{jsxref("String.valueOf", "valueOf")}} 方法,我们可以将字符串对象转换为其对应的基本字符串。</p> + +<pre class="brush: js">console.log(eval(s2.valueOf())); // returns the number 4 +</pre> + +<div class="note"><strong>注意:</strong> 其他的将字符串对象转换成基本字符串的方法可以及参考 <a href="/zh-CN/docs/Web/JavaScript/Typed_arrays/StringView" title="/zh-CN/docs/Web/JavaScript/Typed_arrays/StringView"><code>StringView</code> – a C-like representation of strings based on typed arrays</a>.</div> + +<h2 id="属性">属性</h2> + +<dl> + <dt>{{jsxref("String.prototype")}}</dt> + <dd>可以为 String 对象增加新的属性。</dd> +</dl> + +<h2 id="Methods" name="Methods">方法</h2> + +<dl> + <dt>{{jsxref("String.fromCharCode()")}} </dt> + <dd> <strong>通过一串 Unicode 创建字符串。</strong></dd> +</dl> + +<dl> + <dt>{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}</dt> + <dd>通过一串 码点 创建字符串。</dd> +</dl> + +<div> +<dl> + <dt>{{jsxref("String.raw()")}} {{experimental_inline}}</dt> + <dd>通过模板字符串创建字符串。</dd> +</dl> +</div> + +<h2 id="字符串泛型方法">字符串泛型方法</h2> + +<div class="warning"> +<p>字符串泛型是<strong>非标准的</strong>,<strong>已弃用</strong>,<strong>并且会在不远的</strong><strong>将来删除</strong>。注意,你不能依靠他们的跨浏览器,而不使用下面提供的垫片。</p> +</div> + +<p>应该避免在 Javascript 1.6 (Firefox 浏览器的 JS 引擎)中使用(虽然也支持)将其他对象转化为字符的方法,因为方法并没有成为 ECMA 标准:</p> + +<pre class="brush: js">let num = 15; +console.log(String.replace(num, /5/, '2')); +</pre> + +<p class="brush: js">移除字符串泛型的措施,参见 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Deprecated_string_generics">Warning: String.x is deprecated; use String.prototype.x instead</a>.</p> + +<p class="brush: js"><span style="background-color: #ffffff; color: #4d4e53; font-family: open sans,arial,sans-serif; font-size: 14px; line-height: 21px;">{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}} 在 Javascript 1.6 中同样支持{{jsxref("Global_Objects/Array", "Array")}}。</span></p> + +<h2 id="String_instances" name="String_instances"><code>String</code> 实例</h2> + +<h3 id="属性_2">属性</h3> + +<p>{{page('zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}</p> + +<p><span style="line-height: 1.5;">{{page('zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods')}}</span></p> + +<h2 id="示例">示例 </h2> + +<h3 id="将其他值转换成字符串">将其他值转换成字符串</h3> + +<p>使用 String() 方法将其它对象转化为字符串可以被认为是一种更加安全的做法,虽然该方法底层使用的也是 toString() 方法,但是针对 null/undefined/symbols,String() 方法会有特殊的处理:</p> + +<pre class="brush: js">var outputStrings = []; +for (let i = 0, n = inputValues.length; i < n; ++i) { + outputStrings.push(String(inputValues[i])); +} +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>ECMAScript 1st Edition.</td> + <td>Standard</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5', 'String')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string-objects', 'String')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>0.2</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="sect1"></h2> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{domxref("DOMString")}}</li> + <li><a href="/zh-CN/docs/Web/JavaScript/Typed_arrays/StringView" title="/zh-CN/docs/Web/JavaScript/Typed_arrays/StringView"><code>StringView</code> – a C-like representation of strings based on typed arrays</a></li> + <li><a href="https://developer.mozilla.org/zh-CN/docs/Web/API/DOMString/Binary">Binary strings</a></li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><code><strong>indexOf()</strong></code> 方法返回调用它的 {{jsxref("String")}} 对象中第一次出现的指定值的索引,从 <code>fromIndex</code> 处进行搜索。如果未找到该值,则返回 -1。</p> + +<div>{{EmbedInteractiveExample("pages/js/string-indexof.html")}}</div> + + + +<div class="note"><strong>Note:</strong> For the Array method, see {{jsxref("Array.prototype.indexOf()")}}.</div> + +<h2 id="语法">语法</h2> + +<pre class="notranslate"><var>str</var>.indexOf(<var>searchValue [</var>, <var>fromIndex]</var>)</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>searchValue</code></dt> + <dd>要被查找的字符串值。</dd> + <dd>如果没有提供确切地提供字符串,<a href="https://tc39.github.io/ecma262/#sec-tostring"><var>searchValue</var> 会被强制设置为 <code>"undefined"</code></a>, 然后在当前字符串中查找这个值。</dd> + <dd>举个例子:<code>'undefined'.indexOf()</code> 将会返回0,因为 <code>undefined</code> 在位置0处被找到,但是 <code>'undefine'.indexOf()</code> 将会返回 -1 ,因为字符串 <code>'undefined'</code> 未被找到。</dd> + <dt><code>fromIndex</code> {{optional_inline}}</dt> + <dd>数字表示开始查找的位置。可以是任意整数,默认值为 <code>0</code>。</dd> + <dd>如果 <code>fromIndex</code> 的值小于 <code>0</code>,或者大于 <code><var>str</var>.length</code> ,那么查找分别从 <code>0</code> 和<code><var>str</var>.length</code> 开始。(译者注: <code>fromIndex</code> 的值小于 <code>0</code>,等同于为空情况; <code>fromIndex</code> 的值大于或等于 <code><var>str</var>.length</code> ,那么结果会直接返回 <code>-1</code> 。)</dd> + <dd>举个例子,<code>'hello world'.indexOf('o', -5)</code> 返回 <code>4</code> ,因为它是从位置<code>0</code>处开始查找,然后 <code>o</code> 在位置<code>4</code>处被找到。另一方面,<code>'hello world'.indexOf('o', 11)</code> (或 <code>fromIndex</code> 填入任何大于<code>11</code>的值)将会返回 <code>-1</code> ,因为开始查找的位置<code>11</code>处,已经是这个字符串的结尾了。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>查找的字符串 <code><var>searchValue</var></code><var> </var>的第一次出现的索引,如果没有找到,则返回 <code>-1</code>。</p> + +<p>若被查找的字符串 <code><var>searchValue</var></code><var> </var>是一个空字符串,将会产生“奇怪”的结果。如果 <code>fromIndex</code> 值为空,或者 <code>fromIndex</code> 值小于被查找的字符串的长度,返回值和以下的 <code>fromIndex</code> 值一样:</p> + +<pre class="brush: js notranslate">'hello world'.indexOf('') // 返回 0 +'hello world'.indexOf('', 0) // 返回 0 +'hello world'.indexOf('', 3) // 返回 3 +'hello world'.indexOf('', 8) // 返回 8</pre> + +<p>另外,如果 <code>fromIndex</code> 值大于等于字符串的长度,将会直接返回字符串的长度(<code>str.length</code>):</p> + +<pre class="brush: js notranslate">'hello world'.indexOf('', 11) // 返回 11 +'hello world'.indexOf('', 13) // 返回 11 +'hello world'.indexOf('', 22) // 返回 11</pre> + +<p>从前面一个例子可以看出,被查找的值是空值时,Javascript将直接返回指定的索引值。从后面一个例子可以看出,被查找的值是空值时,Javascript将直接返回字符串的长度。</p> + +<h2 id="描述">描述</h2> + +<p>字符串中的字符被从左向右索引。第一个字符的索引(index)是 <code>0</code>,变量名为 <code>stringName</code> 的字符串的最后一个字符的索引是 <code>stringName.length - 1</code> 。</p> + +<pre class="brush: js notranslate">"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</pre> + +<p id="Example_indexOf_and_case-sensitivity"><code>indexOf</code> 方法是区分大小写的。例如,下面的表达式将返回 <code>-1</code>:</p> + +<pre class="brush: js notranslate">"Blue Whale".indexOf("blue") // 返回 -1 +</pre> + +<h3 id="检测是否存在某字符串">检测是否存在某字符串</h3> + +<p>注意 <code>0</code> 并不会被当成 <code>true</code> ,<code>-1</code> 不会被当成 <code>false</code> 。所以当检测某个字符串是否存在于另一个字符串中时,可使用下面的方法:</p> + +<pre class="notranslate">'Blue Whale'.indexOf('Blue') !== -1 // true +'Blue Whale'.indexOf('Bloe') !== -1 // false +~('Blue Whale'.indexOf('Bloe')) // 0, 这是一种错误用法</pre> + +<h2 id="示例">示例</h2> + +<h3 id="Example_Using_indexOf_and_lastIndexOf" name="Example:_Using_indexOf_and_lastIndexOf">使用<code>indexOf()</code> 和 <code>lastIndexOf()</code></h3> + +<p>下例使用 <code>indexOf()</code> 和 <code>lastIndexOf()</code> 方法定位字符串中 "<code>Brave new world</code>" 的值。</p> + +<pre class="brush: js notranslate">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 +</pre> + +<h3 id="indexOf_和区分大小写"><code>indexOf</code> 和区分大小写</h3> + +<p>下例定义了两个字符串变量。两个变量包含相同的字符串,除了第二个字符串中的某些字符为大写。第一个 <code>log</code> 方法输出 19。但是由于 <code>indexOf</code> 方法区分大小写,因此不会在 <code>myCapString</code> 中发现字符串 <code>“cheddar"</code>,所以,第二个 <code>log</code> 方法会输出 -1。</p> + +<pre class="brush: js notranslate">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</pre> + +<h3 id="使用_indexOf_统计一个字符串中某个字母出现的次数">使用 <code>indexOf</code> 统计一个字符串中某个字母出现的次数</h3> + +<p>在下例中,设置了 <code>count</code> 来记录字母 <code><font face="Consolas, Liberation Mono, Courier, monospace">e</font></code> 在字符串 <code>str</code> 中出现的次数:</p> + +<pre class="brush: js notranslate">// 翻译:生存还是毁灭?这是个问题。(莎士比亚《哈姆雷特》) +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 +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">说明</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.7', 'String.prototype.indexOf')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + + + +<p>{{Compat("javascript.builtins.String.indexOf")}}</p> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("String.prototype.charAt()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> + <li>{{jsxref("String.prototype.includes()")}}</li> + <li>{{jsxref("String.prototype.split()")}}</li> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> +</ul> 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 +--- +<div>{{JSRef}} {{deprecated_header}}</div> + +<p>The <strong><code>italics()</code></strong> method creates an {{HTMLElement("i")}} HTML element that causes a string to be italic.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>str</var>.italics()</code></pre> + +<h2 id="Description">Description</h2> + +<p>The <code>italics()</code> method embeds a string in an <code><i></code> tag: <code>"<i>str</i>"</code>.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_italics()">Using <code>italics()</code></h3> + +<p>The following example uses string methods to change the formatting of a string:</p> + +<pre class="brush: js">var worldString = 'Hello, world'; console.log(worldString.blink()); // Hello, world +console.log(worldString.bold()); // <strong>Hello, world</strong> +console.log(worldString.italics()); //<em>Hello, world</em> +console.log(worldString.strike()); // <s>Hello, world</s></pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.italics', 'String.prototype.italics')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0. Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.italics', 'String.prototype.italics')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("String.prototype.blink()")}}</li> + <li>{{jsxref("String.prototype.bold()")}}</li> + <li>{{jsxref("String.prototype.strike()")}}</li> +</ul> 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 +--- +<p><span style="display: none;"> </span>{{JSRef}}</p> + +<p> <strong><code>lastIndexOf()</code></strong> 方法返回调用{{jsxref("String")}} 对象的指定值最后一次出现的索引,在一个字符串中的指定位置 <code>fromIndex</code>处从后向前搜索。如果没找到这个特定值则返回-1 。</p> + +<p>该方法将从尾到头地检索字符串 <em>str</em>,看它是否含有子串 <em>searchValue</em>。开始检索的位置在字符串的 <em>fromIndex</em> 处或字符串的结尾(没有指定 <em>fromIndex</em> 时)。如果找到一个 <em>searchValue</em>,则返回 <em>searchValue</em> 的第一个字符在 <em>str</em> 中的位置。<em>str</em>中的字符位置是从 0 开始的。</p> + +<h2 id="Syntax" name="Syntax">语法</h2> + +<pre class="syntaxbox"><code><em>str</em>.lastIndexOf(<em>searchValue</em>[, fromIndex])</code></pre> + +<h3 id="Parameters" name="Parameters">参数</h3> + +<dl> + <dt><code>searchValue</code></dt> + <dd>一个字符串,表示被查找的值。如果<code>searchValue</code>是空字符串,则返回<code>fromIndex</code>。</dd> + <dt><code>fromIndex</code>{{optional_inline}}</dt> + <dd>待匹配字符串searchValue的开头一位字符从 str的第fromIndex位开始向左回向查找。<code>fromIndex</code>默认值是 <code>+Infinity</code>。如果 <code>fromIndex >= str.length</code> ,则会搜索整个字符串。如果 <code>fromIndex < 0</code> ,则等同于 <code>fromIndex == 0</code>。</dd> + <dt> + <h3 id="返回值">返回值</h3> + </dt> +</dl> + +<p>返回指定值最后一次出现的索引(该索引仍是以从左至右0开始记数的),如果没找到则返回-1。</p> + +<h2 id="Description" name="Description">描述</h2> + +<p>字符串中的字符被从左向右索引。首字符的索引(index)是 0,最后一个字符的索引是 <code>stringName.length - 1</code>。</p> + +<pre><code>'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</code> +</pre> + +<div class="blockIndicator note"> +<p>Note: <code>'abab'.lastIndexOf('ab', 2)</code> 将返回 2 而不是 0, 因为fromIndex只限制待匹配字符串的开头。</p> +</div> + +<p>(例如'abadefgabm'.lastIndexOf('ab', 7) 返回7,虽然查找的'ab'中的b已经在 index=8的位置了从index=7的a处向左查找仍是能找到自身a加上其后连成ab,因为fromIndex指的是待匹配字符串的开头那一个)</p> + +<h3 id="Example_indexOf_and_case-sensitivity" name="Example:_indexOf_and_case-sensitivity">区分大小写</h3> + +<p><code>lastIndexOf</code> 方法区分大小写。例如,下面的表达式返回 -1:</p> + +<pre class="brush:js">"Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1</pre> + +<h2 id="Examples" name="Examples">示例</h2> + +<h3 id="Example_Using_indexOf_and_lastIndexOf" name="Example:_Using_indexOf_and_lastIndexOf">例子:使用 <code>indexOf</code> 和 <code>lastIndexOf</code></h3> + +<p>下例使用 <code>indexOf</code> 和 <code>lastIndexOf</code> 方法来定位字符串 "<code>Brave new world</code>" 中的值。</p> + +<pre class="brush:js">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 +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.8', 'String.prototype.lastIndexOf')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.lastindexof', 'String.prototype.lastIndexOf')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("String.prototype.charAt()")}}</li> + <li>{{jsxref("String.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.split()")}}</li> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> + <li>{{jsxref("Array.prototype.lastIndexOf()")}}</li> +</ul> 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 +--- +<p>{{JSRef("Global_Objects", "String")}}</p> + +<h2 id="Summary" name="Summary" style="margin-bottom: 20px; line-height: 30px;">概述</h2> + +<p><strong>length</strong> 属性表示一个字符串的长度。</p> + +<h2 id="Description" name="Description" style="margin-bottom: 20px; line-height: 30px;">描述</h2> + +<p>该属性返回字符串中字符编码单元的数量。JavaScript 使用 {{ interwiki("wikipedia", "UTF-16") }} 编码,该编码使用一个 16 比特的编码单元来表示大部分常见的字符,使用两个代码单元表示不常用的字符。因此 length 返回值可能与字符串中实际的字符数量不相同。</p> + +<p>空字符串的 <code>length</code> 为 0。</p> + +<p>静态属性 <strong>String.length</strong> 返回 1。</p> + +<h2 id="Examples" name="Examples" style="margin-bottom: 20px; line-height: 30px;">示例</h2> + +<pre class="brush: js">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" */</pre> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 0px; background: 0px 0px;"> </div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 19px; background: 0px 0px;"> </div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 38px; background: 0px 0px;"> </div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 57px; background: 0px 0px;"> </div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 76px; background: 0px 0px;"> </div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 95px; background: 0px 0px;"> </div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 114px; background: 0px 0px;"> </div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 133px; background: 0px 0px;"> </div> + +<h2 id="规范" style="margin-bottom: 20px; line-height: 30px;">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.5.1', 'String.prototype.length')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性" style="margin-bottom: 20px; line-height: 30px;">浏览器兼容性</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th style="line-height: 16px;">Feature</th> + <th style="line-height: 16px;">Chrome</th> + <th style="line-height: 16px;">Firefox (Gecko)</th> + <th style="line-height: 16px;">Internet Explorer</th> + <th style="line-height: 16px;">Opera</th> + <th style="line-height: 16px;">Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th style="line-height: 16px;">Feature</th> + <th style="line-height: 16px;">Android</th> + <th style="line-height: 16px;">Chrome for Android</th> + <th style="line-height: 16px;">Firefox Mobile (Gecko)</th> + <th style="line-height: 16px;">IE Mobile</th> + <th style="line-height: 16px;">Opera Mobile</th> + <th style="line-height: 16px;">Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also" name="See_also" style="margin-bottom: 20px; line-height: 30px;">相关链接</h2> + +<ul> + <li><a class="external external-icon" href="http://developer.teradata.com/blog/jasonstrimpel/2011/11/javascript-string-length-and-internationalizing-web-applications" style="white-space: pre-line;">JavaScript String.length and Internationalizing Web Applications</a></li> +</ul> 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 +--- +<div>{{JSRef}} {{deprecated_header}}</div> + +<p><strong><code>link()</code></strong> 方法创建一个 HTML 元素 {{HTMLElement("a")}} ,用该字符串作为超链接的显示文本,参数作为指向另一个 URL 的超链接。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code><var>str</var>.link(<var>url</var>)</code></pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>url</code></dt> + <dd>任何能够指定 <code>a</code> 标签的 <code>href</code> 属性的字符串;它应当是有效的 URL(相对或绝对),任何 <code>&</code> 字符将会被转义为 <code>&amp;</code>,任何 <code>"</code> 字符将会被转义为 <code>&quot;</code>。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>一个带有一个 HTML 元素 {{HTMLElement("a")}} 的字符串。</p> + +<h2 id="描述">描述</h2> + +<p>使用 <code>link</code> 方法创建一个超链接 HTML 片段。返回的字符串可以通过 {{ Domxref("document.write") }} 或 {{ Domxref("element.innerHTML") }} 方法添加到文档中。</p> + +<p>使用 <code>link</code> 方法创建的链接将会成为 document.links 数组中的元素。查看 {{ Domxref("document.links") }}。</p> + +<h2 id="Examples" name="Examples">示例</h2> + +<h3 id="例子:使用_link">例子:使用 <code>link</code></h3> + +<p>下例显示一个单词 "MDN" 作为超链接,指向 Mozilla Developer Network。</p> + +<pre class="brush:js">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> +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.link', 'String.prototype.link')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0. Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.link', 'String.prototype.link')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.link")}}</p> + +<h2 id="参见">参见</h2> + +<ul> + <li>{{jsxref("String.prototype.anchor()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><strong><code>localeCompare()</code></strong> 方法返回一个数字来指示一个参考字符串是否在排序顺序前面或之后或与给定字符串相同。</p> + +<p><code>新的 locales 、</code> <code>options</code> 参数能让应用程序定制函数的行为即指定用来排序的语言。 <code>locales</code> 和 <code>options</code> 参数是依赖于具体实现的,在旧的实现中这两个参数是完全被忽略的。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox notranslate"><code><var>referenceStr</var>.localeCompare(<var>compareString</var>[, <var>locales</var>[, <var>options</var>]])</code></pre> + +<h3 id="参数">参数</h3> + +<p>查阅<a href="#浏览器支持">浏览器支持</a>部分来确定哪些浏览器支持 <code>locales</code> 参数和 <code>options</code> 参数, <a href="检查浏览器对扩展参数的支持">在功能检测中检查对 <code>locales</code> 、<code>options </code>参数的支持</a>。</p> + +<dl> + <dt><code>compareString</code></dt> + <dd>用来比较的字符串</dd> + <dt><strong><code><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: #eeeeee;">locales</span></font></code></strong></dt> + <dd>可选。 用来表示一种或多种语言或区域的一个符合 <a href="https://tools.ietf.org/html/rfc5646">BCP 47</a> 标准的字符串或一个字符串数组。 <code>locales</code>参数的一般形式与解释, 详情请参考 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation">Intl page</a>。 下列的 Unicode 扩展关键词是允许的:</dd> + <dd><code><strong>co</strong></code></dd> + <dd>为了某些地域多样的排序规则。可能的值包括: <code>"big5han"</code>, <code>"dict"</code>, <code>"direct"</code>, <code>"ducet"</code>, <code>"gb2312"</code>, <code>"phonebk"</code>, <code>"phonetic"</code>, <code>"pinyin"</code>, <code>"reformed"</code>, <code>"searchjl"</code>, <code>"stroke"</code>, <code>"trad"</code>, <code>"unihan"</code>。 <code>"standard"</code> 和<code>"search"</code> 这两个值是被忽略的; 它们被 <code>options</code> 的属性 <code>usage</code> 代替(往下看)。</dd> + <dd><strong><code>kn</code></strong></dd> + <dd>指定数值排序是否应该被使用, 像是这样 "1" < "2" < "10"。 可能的值是 <code>"true"</code> 和 <code>"false"</code>。 这个选项能被通过<code>options</code> 属性设置或通过 Unicode 扩展。 假如两个都被设置了, 则 <code>options</code> 优先。(<em>"<em>language</em>-<em>region</em>-u-kn-true|false")</em></dd> + <dd><strong><code>kf</code></strong></dd> + <dd>指定是否优先对大写字母或小写字母排序。 可能的值有 <code>"upper"</code>, <code>"lower"</code>, 或 <code>"false"</code> (use the locale's default)。这个选项能被通过<code>options</code> 属性设置或通过 Unicode 扩展。假如两个都被设置了, 则 <code>options</code> 优先。<em>("<em>language</em>-<em>region</em>-u-kf-upper|lower|false")</em></dd> + <dt><code>options</code></dt> + <dd> + <p>可选。 支持下列的一些或全部属性的一个对象:</p> + + <dl> + <dt><code>localeMatcher</code></dt> + <dd>地域匹配算法的使用. 可能的值是 <code>"lookup"</code> 和 <code>"best fit"</code>; 默认的值是 <code>"best fit"</code>。更多相关的资料, 请参考 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation" title="The Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. The constructors for Collator, NumberFormat, and DateTimeFormat objects are properties of the Intl object. This page documents these properties as well as functionality common to the internationalization constructors and other language sensitive functions.">Intl page</a>.</dd> + <dt><code>usage</code></dt> + <dd>指定比较的目标是排序或者是搜索. 可能的值是 <code>"sort"</code> 和 <code>"search"</code>; 默认是 <code>"sort"</code>.</dd> + <dt><code>sensitivity</code></dt> + <dd> + <p>指定排序程序的敏感度(Which differences in the strings should lead to non-zero result values.) 可能的有:</p> + + <ul> + <li><code>"base"</code>: 只有不同的字母字符串比较是不相等的. 举个例子: <code>a ≠ b</code>, <code>a = á</code>, <code>a = A</code>.</li> + <li><code>"accent"</code>: 只有不同的字母或读音比较是不相等的. 举个例子: <code>a ≠ b</code>, <code>a ≠ á</code>, <code>a = A</code>.</li> + <li><code>"case"</code>: 只有不同的字母或大小写比较是不相等的. 举个例子: <code>a ≠ b</code>, <code>a = á</code>, <code>a ≠ A</code>.</li> + <li><code>"variant"</code>: 不同的字母或读音及其它有区别的标志或大小写都是不相等的, 还有其它的差异可能也会考虑到. 举个例子: <code>a ≠ b</code>, <code>a ≠ á</code>, <code>a ≠ A</code>.</li> + </ul> + + <p>The default is <code>"variant"</code> for usage <code>"sort"</code>; it's locale dependent for usage <code>"search"</code>.</p> + </dd> + <dt><code>ignorePunctuation</code></dt> + <dd>指定是否忽略标点. 可能的值是 <code>true</code> and <code>false</code>; 默认为 <code>false</code>.</dd> + <dt><code>numeric</code></dt> + <dd>是否指定使用数字排序, 像这样 "1" < "2" < "10". 可能的值是 <code>true</code> 和 <code>false</code>; 默认为 <code>false</code>. 这个选项能被通过<code>options</code> 属性设置或通过 Unicode 扩展。假如两个都被设置了, 则 <code>options</code> 优先。 实现不用必须支持这个属性.</dd> + <dt><code>caseFirst</code></dt> + <dd>指定大小写有限排序. 可能的值有 <code>"upper"</code>, <code>"lower"</code>, or <code>"false"</code> (use the locale's default); 默认为 <code>"false"</code>. 这个选项能被通过<code>options</code> 属性设置或通过 Unicode 扩展。假如两个都被设置了, 则 <code>options</code> 优先。 实现不用必须支持这个属性.</dd> + </dl> + </dd> + <dd> + <h3 id="返回值"><strong>返回值</strong></h3> + + <p>如果引用字符存在于比较字符之前则为<strong>负数</strong>; 如果引用字符存在于比较字符之后则为<strong>正数</strong>; 相等的时候返回 <strong>0</strong> .</p> + </dd> + <dd>page('/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Collator', 'Parameters')}}</dd> +</dl> + +<h2 id="描述">描述</h2> + +<p>返回一个数字表示是否 <strong>引用字符串</strong> 在排序中位于 <strong>比较字符串</strong> 的前面,后面,或者二者相同。</p> + +<ul> + <li>当 <strong>引用字符串 </strong>在 <strong>比较字符串 </strong>前面时返回 -1</li> + <li>当 <strong>引用字符串</strong> 在 <strong>比较字符串 </strong>后面时返回 1</li> + <li>相同位置时返回 0</li> +</ul> + +<p><strong>切勿依赖于 -1 或 1 这样特定的返回值。</strong>不同浏览器之间(以及不同浏览器版本之间)<strong> </strong>返回的正负数的值各有不同,因为W3C规范中只要求返回值是正值和负值,而没有规定具体的值。一些浏览器可能返回-2或2或其他一些负的、正的值。</p> + +<h2 id="示例">示例</h2> + +<h3 id="使用_localeCompare">使用 <code>localeCompare()</code></h3> + +<pre class="brush: js notranslate">// 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 +</pre> + +<h3 id="检查浏览器对扩展参数的支持">检查浏览器对扩展参数的支持</h3> + +<p><code>locales</code> 和 <code>options</code> 参数还没有被所有浏览器所支持。检查是否被支持, 使用 "i" 参数 (a requirement that illegal language tags are rejected) 判断是否有异常 {{jsxref("RangeError")}}抛出:</p> + +<pre class="brush: js notranslate">function localeCompareSupportsLocales() { + try { + 'foo'.localeCompare('bar', 'i'); + } catch (e) { + return e.name === 'RangeError'; + } + return false; +} +</pre> + +<h3 id="使用_locales_参数">使用 <code>locales 参数</code></h3> + +<p>在不同的语言下 <code>localeCompare()</code> 所提供的结果是不一致的。 为了能让用户得到正确的比较值, 通过使用 <code>locales</code> 参数来提供要比较的语言 (and possibly some fallback languages) :</p> + +<pre class="brush: js notranslate">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 +</pre> + +<h3 id="使用_options_参数">使用 <code>options 参数</code></h3> + +<p><code>localeCompare()</code> 所提供的结果可以通过 <code>options</code> 参数来制定:</p> + +<pre class="brush: js notranslate">// 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 +</pre> + +<h2 id="性能相关">性能相关</h2> + +<p>当比较大量字符串时, 比如比较大量数组时, 最好创建一个{{jsxref("Global_Objects/Collator", "Intl.Collator")}} 对象并使用{{jsxref("Collator.prototype.compare", "compare")}} 属性所提供的函数。</p> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.9', 'String.prototype.localeCompare')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.localecompare', 'String.prototype.localeCompare')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES Int 1.0', '#sec-13.1.1', 'String.prototype.localeCompare')}}</td> + <td>{{Spec2('ES Int 1.0')}}</td> + <td><code>locale</code> and <code>option</code> parameter definitions.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.localeCompare")}}</p> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("Global_Objects/Collator", "Intl.Collator")}}</li> +</ul> 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 +--- +<p>{{JSRef}}</p> + +<p> <strong><code>match()</code> </strong>方法检索返回一个字符串匹配正则表达式的结果。</p> + + +<div>{{EmbedInteractiveExample("pages/js/string-match.html", "shorter")}}</div> + +<div class="hidden">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 <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="Syntax" name="Syntax">语法</h2> + +<pre class="syntaxbox notranslate"><code><em>str</em>.match(regexp)</code></pre> + +<h3 id="Parameters" name="Parameters">参数</h3> + +<dl> + <dt><code>regexp</code></dt> + <dd>一个<a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp" title="JavaScript/Reference/Global Objects/RegExp">正则表达式</a>对象。如果传入一个非正则表达式对象,则会隐式地使用 <code>new RegExp(obj)</code> 将其转换为一个 {{jsxref("RegExp")}} 。如果你没有给出任何参数并直接使用match() 方法 ,你将会得到一 个包含空字符串的 {{jsxref("Array")}} :[""] 。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<ul> + <li><span style="line-height: 1.572;">如果使用g标志,则将返回与完整正则表达式匹配的所有结果,但不会返回捕获组。</span></li> + <li>如果未使用g标志,则仅返回第一个完整匹配及其相关的捕获组<span style="line-height: 1.572;">(<code>Array</code>)</span>。 在这种情况下,返回的项目将具有如下所述的其他属性。</li> +</ul> + +<h4 id="附加属性">附加属性</h4> + +<p>如上所述,匹配的结果包含如下所述的附加特性。</p> + +<ul> + <li><code>groups</code>: 一个捕获组数组 或 {{jsxref("undefined")}}(如果没有定义命名捕获组)。</li> + <li><code>index</code>: 匹配的结果的开始位置</li> + <li><code>input</code>: 搜索的字符串.</li> +</ul> + +<dl> + <dd>一个{{jsxref("Array")}},其内容取决于global(<code>g</code>)标志的存在与否,如果未找到匹配则为{{jsxref("null")}}。</dd> +</dl> + +<h2 id="Description" name="Description">描述</h2> + +<p>如果正则表达式不包含 <code>g </code>标志,<code>str.match()</code> 将返回与 {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}}. 相同的结果。</p> + +<h3 id="Notes" name="Notes">参看:<code>RegExp</code> 方法</h3> + +<ul> + <li>如果你需要知道一个字符串是否与一个正则表达式匹配 {{jsxref("RegExp")}} ,可使用 {{jsxref("RegExp.prototype.test()", "RegExp.test()")}} 。</li> + <li>如果你只是需要第一个匹配结果,你也可以使用 {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}} 。</li> + <li>如果你想要获得捕获组,并且设置了全局标志,你需要用 {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}} 或者 {{jsxref("String.prototype.matchAll()", " String.prototype.matchAll()")}}</li> +</ul> + +<h2 id="Examples" name="Examples">示例</h2> + +<h3 id="Example_Using_match" name="Example:_Using_match">例子:使用 <code>match</code></h3> + +<p>在下例中,使用 <code>match</code> 查找 "<code>Chapter</code>" 紧跟着 1 个或多个数值字符,再紧跟着一个小数点和数值字符 0 次或多次。正则表达式包含 <code>i</code> 标志,因此大小写会被忽略。</p> + +<pre class="brush: js line-numbers language-js notranslate"><code class="language-js"><span class="keyword token">var</span> str <span class="operator token">=</span> <span class="string token">'For more information, see Chapter 3.4.5.1'</span><span class="punctuation token">;</span> +<span class="keyword token">var</span> re <span class="operator token">=</span> <span class="regex token">/see (chapter \d+(\.\d)*)/i</span><span class="punctuation token">;</span> +<span class="keyword token">var</span> found <span class="operator token">=</span> str<span class="punctuation token">.</span><span class="function token">match</span><span class="punctuation token">(</span>re<span class="punctuation token">)</span><span class="punctuation token">;</span> + +console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>found<span class="punctuation token">)</span><span class="punctuation token">;</span> + +<span class="comment token">// logs [ 'see Chapter 3.4.5.1',</span> +<span class="comment token">// 'Chapter 3.4.5.1',</span> +<span class="comment token">// '.1',</span> +<span class="comment token">// index: 22,</span> +<span class="comment token">// input: 'For more information, see Chapter 3.4.5.1' ]</span> + +<span class="comment token">// 'see Chapter 3.4.5.1' 是整个匹配。</span> +<span class="comment token">// 'Chapter 3.4.5.1' 被'(chapter \d+(\.\d)*)'捕获。</span> +<span class="comment token">// '.1' 是被'(\.\d)'捕获的最后一个值。</span> +<span class="comment token">// 'index' 属性(22) 是整个匹配从零开始的索引。</span> +<span class="comment token">// 'input' 属性是被解析的原始字符串。</span></code></pre> + +<h3 id="Example_Using_global_and_ignore_case_flags_with_match" name="Example:_Using_global_and_ignore_case_flags_with_match">例子:<code>match</code> 使用全局(global)和忽略大小写(ignore case)标志</h3> + +<p>下例展示了 <code>match</code> 使用 global 和 ignore case 标志。A-E、a-e 的所有字母将会作为一个数组的元素返回。</p> + +<pre class="brush: js line-numbers language-js notranslate"><code class="language-js"><span class="keyword token">var</span> str <span class="operator token">=</span> <span class="string token">'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'</span><span class="punctuation token">;</span> +<span class="keyword token">var</span> regexp <span class="operator token">=</span> <span class="regex token">/[A-E]/gi</span><span class="punctuation token">;</span> +<span class="keyword token">var</span> matches_array <span class="operator token">=</span> str<span class="punctuation token">.</span><span class="function token">match</span><span class="punctuation token">(</span>regexp<span class="punctuation token">)</span><span class="punctuation token">;</span> + +console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>matches_array<span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="comment token">// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']</span></code></pre> + +<h3 id="使用match,不传参数"><code>使用match(),不传参数 </code></h3> + +<pre class="brush: js line-numbers language-js notranslate"><code class="language-js"><span class="keyword token">var</span> str <span class="operator token">=</span> <span class="string token">"Nothing will come of nothing."</span><span class="punctuation token">;</span> + +str<span class="punctuation token">.</span><span class="function token">match</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// returns [""]</span></code></pre> + +<h3 id="一个非正则表达式对象作为参数">一个非正则表达式对象作为参数</h3> + +<p>当参数是一个字符串或一个数字,它会使用new RegExp(obj)来隐式转换成一个 {{jsxref("RegExp")}}。如果它是一个有正号的正数,RegExp() 方法将忽略正号。</p> + +<pre class="brush: js line-numbers language-js notranslate"><code class="language-js"><span class="keyword token">var</span> str1 <span class="operator token">=</span> <span class="string token">"NaN means not a number. Infinity contains -Infinity and +Infinity in JavaScript."</span><span class="punctuation token">,</span> + str2 <span class="operator token">=</span> <span class="string token">"My grandfather is 65 years old and My grandmother is 63 years old."</span><span class="punctuation token">,</span> + str3 <span class="operator token">=</span> <span class="string token">"The contract was declared null and void."</span><span class="punctuation token">;</span> +str1<span class="punctuation token">.</span><span class="function token">match</span><span class="punctuation token">(</span><span class="string token">"number"</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// "number" 是字符串。返回["number"]</span> +str1<span class="punctuation token">.</span><span class="function token">match</span><span class="punctuation token">(</span><span class="number token">NaN</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// NaN的类型是number。返回["NaN"]</span> +str1<span class="punctuation token">.</span><span class="function token">match</span><span class="punctuation token">(</span><span class="number token">Infinity</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// Infinity的类型是number。返回["Infinity"]</span> +str1<span class="punctuation token">.</span><span class="function token">match</span><span class="punctuation token">(</span><span class="operator token">+</span><span class="number token">Infinity</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// 返回["Infinity"]</span> +str1<span class="punctuation token">.</span><span class="function token">match</span><span class="punctuation token">(</span><span class="operator token">-</span><span class="number token">Infinity</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// 返回["-Infinity"]</span> +str2<span class="punctuation token">.</span><span class="function token">match</span><span class="punctuation token">(</span><span class="number token">65</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// 返回["65"]</span> +str2<span class="punctuation token">.</span><span class="function token">match</span><span class="punctuation token">(</span><span class="operator token">+</span><span class="number token">65</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// 有正号的number。返回["65"]</span> +str3<span class="punctuation token">.</span><span class="function token">match</span><span class="punctuation token">(</span><span class="keyword token">null</span><span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="comment token">// 返回["null"]</span></code></pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.10', 'String.prototype.match')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.match', 'String.prototype.match')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.match', 'String.prototype.match')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Firefox_特殊注意">Firefox 特殊注意</h2> + +<ul> + <li>从Gecko 27 {{geckoRelease(27)}}开始,此方法遵守ECMAScript 规范。当使用全局正则表达式调用 <code>match()时,</code>{{jsxref("RegExp.lastIndex")}} 属性(如果指定)会重置为 <code>0</code> ({{bug(501739)}})。</li> + <li>从 Gecko 39 {{geckoRelease(39)}}开始,不赞成使用非标准的标志参数,并抛出一个控制台警告({{bug(1142351)}})。</li> + <li>从 Gecko 47 {{geckoRelease(47)}} 开始 , non-release builds不再支持非标准的标志参数,并且将完全移除({{bug(1245801)}})。</li> + <li>从 Gecko 49 {{geckoRelease(49)}} 开始 , 不再支持非标准的标志参数 ({{bug(1108382)}}).</li> +</ul> + +<h2 id="See_also" name="See_also">相关链接</h2> + +<ul> + <li>{{jsxref("RegExp")}}</li> + <li>{{jsxref("RegExp.prototype.exec()")}}</li> + <li>{{jsxref("RegExp.prototype.test()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><strong><code>matchAll()</code></strong> 方法返回一个包含所有匹配正则表达式的结果及分组捕获组的迭代器。</p> + +<div>{{EmbedInteractiveExample("pages/js/string-matchall.html")}}</div> + + + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox notranslate"><var>str</var>.matchAll(<var>regexp</var>)</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>regexp</code></dt> +</dl> + +<p> 正则表达式对象。如果所传参数不是一个正则表达式对象,则会隐式地使用 <code>new RegExp(obj)</code> 将其转换为一个 <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/RegExp" title="此页面仍未被本地化, 期待您的翻译!"><code>RegExp</code></a> 。</p> + +<p> <code>RegExp</code>必须是设置了全局模式<code>g</code>的形式,否则会抛出异常<code>TypeError</code>。</p> + +<h3 id="返回值">返回值</h3> + +<p>一个迭代器(不可重用,结果耗尽需要再次调用方法,获取一个新的迭代器)。</p> + +<h2 id="例子">例子</h2> + +<h3 id="Regexp.exec_和_matchAll">Regexp.exec() 和 matchAll()</h3> + +<p>在 <code>matchAll</code> 出现之前,通过在循环中调用 <code>regexp.exec()</code> 来获取所有匹配项信息(regexp 需使用 <code>/g</code> 标志):</p> + +<pre class="brush: js notranslate">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." +}</pre> + +<p>如果使用 <code>matchAll</code> ,就可以不必使用 while 循环加 exec 方式(且正则表达式需使用 <code>/g</code> 标志)。使用 <code>matchAll</code> 会得到一个迭代器的返回值,配合 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></code>, <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">array spread</a>, 或者 {{jsxref("Array.from()")}} 可以更方便实现功能:</p> + +<pre class="brush: js notranslate">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" ]</pre> + +<p>如果没有 <code>/g</code> 标志,<code>matchAll</code> 会抛出异常。</p> + +<pre class="brush: js notranslate">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</pre> + +<p><code>matchAll</code> 内部做了一个 regexp 的复制,所以不像 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec">regexp.exec</a>, <code>lastIndex</code> 在字符串扫描时不会改变。</p> + +<pre class="brush: js notranslate">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" ] +</pre> + +<h3 id="捕获组的更佳途径">捕获组的更佳途径</h3> + +<p><code>matchAll</code> 的另外一个亮点是更好地获取捕获组。因为当使用 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match">match()</a></code> 和 <code>/g</code> 标志方式获取匹配信息时,捕获组会被忽略:</p> + +<pre class="brush: js notranslate">var regexp = /t(e)(st(\d?))/g; +var str = 'test1test2'; + +str.match(regexp); +// Array ['test1', 'test2']</pre> + +<p>使用 <code>matchAll</code> 可以通过如下方式获取分组捕获:</p> + +<pre class="brush: js notranslate">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] +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.matchall', 'String.prototype.matchAll')}}</td> + <td>{{Spec2('ESDraft')}}</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.matchAll")}}</p> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("RegExp")}}</li> + <li>{{jsxref("RegExp.prototype.exec()")}}</li> + <li>{{jsxref("RegExp.prototype.test()")}}</li> +</ul> 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 +--- +<p>{{JSRef}}</p> + +<p><strong>normalize()</strong> 方法会按照指定的一种 Unicode 正规形式将当前字符串正规化。(如果该值不是字符串,则首先将其转换为一个字符串)。</p> + +<div>{{EmbedInteractiveExample("pages/js/string-normalize.html", "taller")}}</div> + + + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code><var>str</var>.normalize([<var>form</var>])</code></pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code><var>form</var></code> {{optional_inline}}</dt> + <dd> + <p>四种 Unicode 正规形式(Unicode Normalization Form)<code>"NFC"</code>、<code>"NFD"</code>、<code>"NFKC"</code>,或 <code>"NFKD"</code> 其中的一个, 默认值为 <code>"NFC"</code>。</p> + + <p>这四个值的含义分别如下:</p> + + <dl> + <dt><code>"NFC"</code></dt> + <dd>Canonical Decomposition, followed by Canonical Composition.</dd> + <dt><code>"NFD"</code></dt> + <dd>Canonical Decomposition.</dd> + <dt><code>"NFKC"</code></dt> + <dd>Compatibility Decomposition, followed by Canonical Composition.</dd> + <dt><code>"NFKD"</code></dt> + <dd>Compatibility Decomposition.</dd> + </dl> + </dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>含有给定字符串的 Unicode 规范化形式的字符串。</p> + +<h3 id="可能出现的异常">可能出现的异常</h3> + +<dl> + <dt>{{jsxref("RangeError")}}</dt> + <dd>如果给 <code>form</code> 传入了上述四个字符串以外的参数,则会抛出 <span><code>RangeError</code> 异常。</span></dd> +</dl> + +<h2 id="描述">描述</h2> + +<p>Unicode assigns a unique numerical value, called a <em>code point</em>, to each character. For example, the code point for <code>"A"</code> 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 <code>"ñ"</code> for example can be represented by either of:</p> + +<ul> + <li>The single code point U+00F1.</li> + <li>The code point for <code>"n"</code> (U+006E) followed by the code point for the combining tilde (U+0303).</li> +</ul> + +<pre class="brush: js">let string1 = '\u00F1'; +let string2 = '\u006E\u0303'; + +console.log(string1); // ñ +console.log(string2); // ñ +</pre> + +<p>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.</p> + +<pre class="brush: js">let string1 = '\u00F1'; // ñ +let string2 = '\u006E\u0303'; // ñ + +console.log(string1 === string2); // false +console.log(string1.length); // 1 +console.log(string2.length); // 2 +</pre> + +<p>The <code>normalize()</code> 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 <strong>canonical equivalence</strong> and the other based on <strong>compatibility</strong>.</p> + +<h3 id="Canonical_equivalence_normalization">Canonical equivalence normalization</h3> + +<p>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).</p> + +<p>You can use <code>normalize()</code> using the <code>"NFD"</code> or <code>"NFC"</code> 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 <code>"ñ"</code>:</p> + +<pre class="brush: js">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 +</pre> + +<h4 id="Composed_and_decomposed_forms">Composed and decomposed forms</h4> + +<p>Note that the length of the normalized form under <code>"NFD"</code> is <code>2</code>. That's because <code>"NFD"</code> gives you the <strong>decomposed</strong> version of the canonical form, in which single code points are split into multiple combining ones. The decomposed canonical form for <code>"ñ"</code> is <code>"\u006E\u0303"</code>.</p> + +<p>You can specify <code>"NFC"</code> to get the <strong>composed</strong> canonical form, in which multiple code points are replaced with single code points where possible. The composed canonical form for <code>"ñ"</code> is <code>"\u00F1"</code>:</p> + +<pre class="brush: js">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</pre> + +<h3 id="Compatibility_normalization">Compatibility normalization</h3> + +<p>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.</p> + +<p>All canonically equivalent sequences are also compatible, but not vice versa.</p> + +<p>For example, the code point U+FB00 represents the <a href="/en-US/docs/Glossary/Ligature">ligature</a> <code>"ff"</code>. It is compatible with two consecutive U+0066 code points (<code>"ff"</code>).</p> + +<p>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.</p> + +<p>You can use <code>normalize()</code> using the <code>"NFKD"</code> or <code>"NFKC"</code> arguments to produce a form of the string that will be the same for all compatible strings:</p> + +<pre class="brush: js">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 +</pre> + +<p>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 <code>"f"</code>. But it may not be appropriate for display, because the visual representation is different.</p> + +<p>As with canonical normalization, you can ask for decomposed or composed compatible forms by passing <code>"NFKD"</code> or <code>"NFKC"</code>, respectively.</p> + +<h2 id="示例">示例</h2> + +<h3 id="使用_normalize">使用 <code>normalize()</code></h3> + +<pre class="brush:js;">// 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" +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.normalize', 'String.prototype.normalize')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-string.prototype.normalize', 'String.prototype.normalize')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.normalize")}}</p> + +<h2 id="参见">参见</h2> + +<ul> + <li><a href="http://www.unicode.org/reports/tr15/">Unicode Standard Annex #15, Unicode Normalizatoin Forms</a></li> + <li><a href="http://zh.wikipedia.org/zh-cn/Unicode%E7%AD%89%E5%83%B9%E6%80%A7">Unicode 等价性</a></li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><strong><code>padEnd()</code></strong> 方法会用一个字符串填充当前字符串(如果需要的话则重复填充),返回填充后达到指定长度的字符串。从当前字符串的末尾(右侧)开始填充。</p> + +<div>{{EmbedInteractiveExample("pages/js/string-padend.html")}}</div> + +<div class="hidden">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 <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox notranslate"><var>str</var>.padEnd(<var>targetLength</var> [, <var>padString</var>])</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>targetLength</code></dt> + <dd>当前字符串需要填充到的目标长度。如果这个数值小于当前字符串的长度,则返回当前字符串本身。</dd> + <dt><code>padString</code> {{optional_inline}}</dt> + <dd>填充字符串。如果字符串太长,使填充后的字符串长度超过了目标长度,则只保留最左侧的部分,其他部分会被截断。此参数的缺省值为 " "(U+0020)。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>在原字符串末尾填充指定的填充字符串直到目标长度所形成的新字符串。</p> + +<h2 id="示例">示例</h2> + +<pre class="brush: js notranslate">'abc'.padEnd(10); // "abc " +'abc'.padEnd(10, "foo"); // "abcfoofoof" +'abc'.padEnd(6, "123456"); // "abc123" +'abc'.padEnd(1); // "abc" +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>如果原生环境不支持该方法,在其他代码之前先运行下面的代码,将创建 <code>String.prototype.padEnd()</code> 方法。</p> + +<pre class="brush: js notranslate">// 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); + } + }; +} +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.padend', 'String.prototype.padEnd')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>在 ECMAScript 2017 中首次被定义。</td> + </tr> + <tr> + <td>{{SpecName('ES8', '#sec-string.prototype.padend', 'String.prototype.padEnd')}}</td> + <td>{{Spec2('ES8')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.padEnd")}}</p> + +<h2 id="另请参阅">另请参阅</h2> + +<ul> + <li>{{jsxref("String.prototype.padStart()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><strong><code>padStart()</code></strong> 方法用另一个字符串填充当前字符串(如果需要的话,会重复多次),以便产生的字符串达到给定的长度。从当前字符串的左侧开始填充。</p> + +<div>{{EmbedInteractiveExample("pages/js/string-padstart.html")}}</div> + +<div class="hidden">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 <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox notranslate"><var>str</var>.padStart(<var>targetLength</var> [, <var>padString</var>])</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>targetLength</code></dt> + <dd>当前字符串需要填充到的目标长度。如果这个数值小于当前字符串的长度,则返回当前字符串本身。</dd> + <dt><code>padString</code> {{optional_inline}}</dt> + <dd>填充字符串。如果字符串太长,使填充后的字符串长度超过了目标长度,则只保留最左侧的部分,其他部分会被截断。此参数的默认值为 " "(U+0020)。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>在原字符串开头填充指定的填充字符串直到目标长度所形成的新字符串。</p> + +<h2 id="示例">示例</h2> + +<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">'abc'.padStart(10); // " abc" +'abc'.padStart(10, "foo"); // "foofoofabc" +'abc'.padStart(6,"123465"); // "123abc" +'abc'.padStart(8, "0"); // "00000abc" +'abc'.padStart(1); // "abc"</code></pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>如果原生环境不支持该方法,在其他代码之前先运行下面的代码,将创建 <code>String.prototype.padStart()</code> 方法。</p> + +<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">// 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); + } + }; +}</code> +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.padstart', 'String.prototype.padStart')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>在 ECMAScript 2017 中首次被定义。</td> + </tr> + <tr> + <td>{{SpecName('ES8', '#sec-string.prototype.padstart', 'String.prototype.padStart')}}</td> + <td>{{Spec2('ES8')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.padStart")}}</p> + +<h2 id="另请参阅">另请参阅</h2> + +<ul> + <li>{{jsxref("String.prototype.padEnd()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p> <code><strong>String.prototype</strong></code> 属性表示 {{jsxref("String")}}原型对象。</p> + +<div>{{js_property_attributes(0,0,0)}}</div> + +<h2 id="Description" name="Description">描述</h2> + +<p>所有 {{jsxref("String")}} 的实例都继承自 <code>String.prototype</code>. 任何String.prototype上的改变都会影响到所有的 {{jsxref("String")}} <code>实例。</code></p> + +<h2 id="Properties" name="Properties">属性</h2> + +<dl> + <dt><code>String.prototype.constructor</code></dt> + <dd>用于创造对象的原型对象的特定的函数。</dd> + <dt>{{jsxref("String.prototype.length")}}</dt> + <dd>返回了字符串的长度。</dd> + <dt><em>N</em></dt> + <dd>用于访问第N个位置的字符,其中N是小于 {{jsxref("String.length", "length")}} 和 0之间的正整数。这些属性都是“只读”性质,不能编辑。</dd> +</dl> + +<h2 id="Methods" name="Methods">方法</h2> + +<h3 id="Methods_unrelated_to_HTML" name="Methods_unrelated_to_HTML">跟HTML无关的方法</h3> + +<dl> + <dt>{{jsxref("String.prototype.charAt()")}}</dt> + <dd>返回特定位置的字符。</dd> + <dt>{{jsxref("String.prototype.charCodeAt()")}}</dt> + <dd>返回表示给定索引的字符的Unicode的值。</dd> + <dt>{{jsxref("String.prototype.codePointAt()")}}</dt> + <dd>返回使用UTF-16编码的给定位置的值的非负整数。</dd> + <dt>{{jsxref("String.prototype.concat()")}}</dt> + <dd>连接两个字符串文本,并返回一个新的字符串。</dd> + <dt>{{jsxref("String.prototype.includes()")}}</dt> + <dd>判断一个字符串里是否包含其他字符串。</dd> + <dt>{{jsxref("String.prototype.endsWith()")}}</dt> + <dd>判断一个字符串的是否以给定字符串结尾,结果返回布尔值。</dd> + <dt>{{jsxref("String.prototype.indexOf()")}}</dt> + <dd>从字符串对象中返回首个被发现的给定值的索引值,如果没有找到则返回-1。</dd> + <dt>{{jsxref("String.prototype.lastIndexOf()")}}</dt> + <dd>从字符串对象中返回最后一个被发现的给定值的索引值,如果没有找到则返回-1。</dd> + <dt>{{jsxref("String.prototype.localeCompare()")}}</dt> + <dd>返回一个数字表示是否引用字符串在排序中位于比较字符串的前面,后面,或者二者相同。</dd> + <dt>{{jsxref("String.prototype.match()")}}</dt> + <dd>使用正则表达式与字符串相比较。</dd> + <dt>{{jsxref("String.prototype.normalize()")}}</dt> + <dd>返回调用字符串值的Unicode标准化形式。</dd> + <dt>{{jsxref("String.prototype.padEnd()")}}</dt> + <dd>在当前字符串尾部填充指定的字符串, 直到达到指定的长度。 返回一个新的字符串。</dd> + <dt>{{jsxref("String.prototype.padStart()")}}</dt> + <dd> + <p>在当前字符串头部填充指定的字符串, 直到达到指定的长度。 返回一个新的字符串。</p> + </dd> + <dt>{{jsxref("String.prototype.quote()")}} {{ obsolete_inline }}</dt> + <dd>设置嵌入引用的引号类型。</dd> + <dt>{{jsxref("String.prototype.repeat()")}}</dt> + <dd>返回指定重复次数的由元素组成的字符串对象。</dd> + <dt>{{jsxref("String.prototype.replace()")}}</dt> + <dd>被用来在正则表达式和字符串直接比较,然后用新的子串来替换被匹配的子串。</dd> + <dt>{{jsxref("String.prototype.search()")}}</dt> + <dd>对正则表达式和指定字符串进行匹配搜索,返回第一个出现的匹配项的下标。</dd> + <dt>{{jsxref("String.prototype.slice()")}}</dt> + <dd>摘取一个字符串区域,返回一个新的字符串。</dd> + <dt>{{jsxref("String.prototype.split()")}}</dt> + <dd>通过分离字符串成字串,将字符串对象分割成字符串数组。</dd> + <dt>{{jsxref("String.prototype.startsWith()")}}</dt> + <dd>判断字符串的起始位置是否匹配其他字符串中的字符。</dd> + <dt>{{jsxref("String.prototype.substr()")}}</dt> + <dd>通过指定字符数返回在指定位置开始的字符串中的字符。</dd> + <dt>{{jsxref("String.prototype.substring()")}}</dt> + <dd>返回在字符串中指定两个下标之间的字符。</dd> + <dt>{{jsxref("String.prototype.toLocaleLowerCase()")}}</dt> + <dd>根据当前区域设置,将符串中的字符转换成小写。对于大多数语言来说,{{jsxref("String.toLowerCase", "toLowerCase")}}的返回值是一致的。</dd> + <dt>{{jsxref("String.prototype.toLocaleUpperCase()")}}</dt> + <dd>根据当前区域设置,将字符串中的字符转换成大写,对于大多数语言来说,{{jsxref("String.toUpperCase", "toUpperCase")}}的返回值是一致的。</dd> + <dt>{{jsxref("String.prototype.toLowerCase()")}}</dt> + <dd>将字符串转换成小写并返回。</dd> + <dt>{{jsxref("String.prototype.toSource()")}} {{ Non-standard_inline() }}</dt> + <dd>返回一个对象文字代表着特定的对象。你可以使用这个返回值来创建新的对象。重写 {{jsxref("Object.prototype.toSource")}} 方法。</dd> + <dt>{{jsxref("String.prototype.toString()")}}</dt> + <dd>返回用字符串表示的特定对象。重写 {{jsxref("Object.prototype.toString")}} 方法。</dd> + <dt>{{jsxref("String.prototype.toUpperCase()")}}</dt> + <dd>将字符串转换成大写并返回。</dd> + <dt>{{jsxref("String.prototype.trim()")}}</dt> + <dd>从字符串的开始和结尾去除空格。参照部分 ECMAScript 5 标准。</dd> + <dt>{{jsxref("String.prototype.trimStart()")}}</dt> + <dt>{{jsxref("String.prototype.trimLeft()")}} {{ Non-standard_inline() }}</dt> + <dd>从字符串的左侧去除空格。</dd> + <dt>{{jsxref("String.prototype.trimEnd()")}}</dt> + <dt>{{jsxref("String.prototype.trimRight()")}} {{ Non-standard_inline() }}</dt> + <dd>从字符串的右侧去除空格。</dd> + <dt>{{jsxref("String.prototype.valueOf()")}}</dt> + <dd>返回特定对象的原始值。重写 {{jsxref("Object.prototype.valueOf")}} 方法。</dd> + <dt>{{jsxref("String.prototype.@@iterator()", "String.prototype[@@iterator]()")}}</dt> + <dd>返回一个新的迭代器对象,该对象遍历字符串值的索引位置,将每个索引值作为字符串值返回。</dd> +</dl> + +<h3 id="HTML_wrapper_methods" name="HTML_wrapper_methods">HTML wrapper methods</h3> + +<p>下面的方法被限制使用,因为只对可用的HTML标签和属性提供部分支持。</p> + +<dl> + <dt>{{jsxref("String.prototype.anchor()")}}</dt> + <dd><code><a href="https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/a#attr-name"><a name="name"></a></code> (hypertext target)</dd> + <dt>{{jsxref("String.prototype.big()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("big")}}</dd> + <dt>{{jsxref("String.prototype.blink()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("blink")}}</dd> + <dt>{{jsxref("String.prototype.bold()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("b")}}</dd> + <dt>{{jsxref("String.prototype.fixed()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("tt")}}</dd> + <dt>{{jsxref("String.prototype.fontcolor()")}} {{deprecated_inline}}</dt> + <dd><a href="https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/font#attr-color"><code><font color="<em>color</em>"></code></a></dd> + <dt>{{jsxref("String.prototype.fontsize()")}} {{deprecated_inline}}</dt> + <dd><a href="https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/font#attr-size"><code><font size="<em>size</em>"></code></a></dd> + <dt>{{jsxref("String.prototype.italics()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("i")}}</dd> + <dt>{{jsxref("String.prototype.link()")}}</dt> + <dd><a class="external" href="https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/a#attr-href"><code><a href="<em>url</em>"></code></a> (link to URL)</dd> + <dt>{{jsxref("String.prototype.small()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("small")}}</dd> + <dt>{{jsxref("String.prototype.strike()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("strike")}}</dd> + <dt>{{jsxref("String.prototype.sub()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("sub")}}</dd> + <dt>{{jsxref("String.prototype.sup()")}} {{deprecated_inline}}</dt> + <dd>{{HTMLElement("sup")}}</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + <tr> + <td>ECMAScript 1st Edition.</td> + <td>Standard</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.3.1', 'String.prototype')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype', 'String.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype', 'String.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.prototype")}}</p> + +<h2 id="更多">更多</h2> + +<ul> + <li>{{jsxref("Global_Objects/String", "String")}}</li> + <li>{{jsxref("Function.prototype")}}</li> +</ul> 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 +--- +<div>{{obsolete_header("37")}}</div> + +<div>{{JSRef("Global_Objects", "String")}}{{Non-standard_header}}</div> + +<h2 id="Summary" name="Summary">概述</h2> + +<p>将字符串中包含的特殊字符进行转义(反斜杠),然后在字符串两边各加上一个双引号(<code>"</code>)并返回,并不修改原字符串.</p> + +<h2 id="Syntax" name="Syntax">语法</h2> + +<pre class="syntaxbox"><code><em>str</em>.quote()</code></pre> + +<h2 id="Examples" name="Examples">示例</h2> + +<table class="fullwidth-table"> + <thead> + <tr> + <th class="header" scope="col"><code>str</code></th> + <th class="header" scope="col"><code>str.quote()</code></th> + <th class="header" scope="col"><code><a href="/zh-CN/docs/JavaScript/Reference/Global_Objects/eval" title="JavaScript/Reference/Global_Objects/eval">eval</a>(str.quote())</code></th> + </tr> + </thead> + <tbody> + <tr> + <td><code>Hello world!</code></td> + <td><code>"Hello world!"</code></td> + <td><code>Hello world!</code></td> + </tr> + <tr> + <td><code>Hello<br> + world!</code></td> + <td><code>"Hello\n\tworld!"</code></td> + <td><code>Hello<br> + world!</code></td> + </tr> + <tr> + <td><code>" \ — '</code></td> + <td><code>"\" \\ \u2014 '"</code></td> + <td><code>" \ — '</code></td> + </tr> + </tbody> +</table> + +<h2 id="Specifications" name="Specifications">规范</h2> + +<p>不在任何规范中。实现于 JavaScript 1.3.</p> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also" name="See_also">相关链接</h2> + +<ul> + <li><code><a href="/zh-CN/docs/JavaScript/Reference/Global_Objects/JSON/stringify" title="JavaScript/Reference/Global_Objects/JSON/stringify">JSON.stringify</a></code></li> +</ul> 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 +--- +<div>{{JSRef()}}</div> + +<p><strong>String.raw()</strong> 是一个<a href="/zh-CN/docs/Web/JavaScript/Reference/template_strings">模板字符串</a>的标签函数,它的作用类似于 Python 中的字符串前缀 <code>r</code> 和 C# 中的字符串前缀 <code>@</code>(还是有点区别的,详见隔壁 Chromium 那边的<a href="https://bugs.chromium.org/p/v8/issues/detail?id=5016">这个 issue</a>),是用来获取一个模板字符串的原始字符串的,比如说,占位符(例如 <code>${foo}</code>)会被处理为它所代表的其他字符串,而转义字符(例如 <code>\n</code>)不会。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code>String.raw(<var>callSite</var>, <var>...substitutions</var>) + +String.raw`templateString` +</code></pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>callSite</code></dt> + <dd>一个模板字符串的“调用点对象”。类似<code>{ raw: ['foo', 'bar', 'baz'] }</code>。</dd> + <dt><code>...substitutions</code></dt> + <dd>任意个可选的参数,表示任意个内插表达式对应的值。</dd> + <dt><code>templateString</code></dt> + <dd>模板字符串,可包含占位符(<code>${...}</code>)。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>给定模板字符串的原始字符串。</p> + +<h3 id="异常">异常</h3> + +<dl> + <dt><code>{{jsxref("TypeError")}}</code></dt> + <dd>如果第一个参数没有传入一个格式正确的对象,则会抛出 <code>TypeError</code> 异常。</dd> +</dl> + +<h2 id="描述">描述</h2> + +<p>在大多数情况下, <code>String.raw()</code>是用来处理模版字符串的. 不要被上面复杂的参数要求吓到,因为像所有的 <a href="/en-US/docs/Web/JavaScript/Reference/template_strings#Tagged_template_literals">tag functions</a>一样,你通常不需要把它看成一个普通函数,你只需要把它放在模板字符串前面就可以了,而不是在它后面加个括号和一堆参数来调用它,引擎会替你去调用它。</p> + +<p><code>String.raw()</code> 是唯一一个内置的模板字符串标签函数,因为它太常用了。不过它并没有什么特殊能力,你自己也可以实现一个和它功能一模一样的标签函数。</p> + +<h2 id="示例">示例</h2> + +<h3 id="使用_String.raw">使用 <code>String.raw()</code></h3> + +<pre class="brush: js">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' +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-string.raw', 'String.raw')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.raw', 'String.raw')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.raw")}}</p> + +<h2 id="参见">参见</h2> + +<ul> + <li><a href="/zh-CN/docs/Web/JavaScript/Reference/template_strings">模板字符串</a></li> + <li>{{jsxref("String")}}</li> + <li><a href="/zh-CN/docs/Web/JavaScript/Reference/Lexical_grammar">JavaScript 词法</a></li> +</ul> 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 +--- +<p>{{JSRef}}</p> + +<p><strong><code>repeat()</code></strong> 构造并返回一个新字符串,该字符串包含被连接在一起的指定数量的字符串的副本。</p> + +<h2 id="Syntax" name="Syntax">语法</h2> + +<pre class="syntaxbox notranslate"><code><var>str</var>.repeat(<var>count</var>)</code></pre> + +<h3 id="Parameters" name="Parameters">参数</h3> + +<dl> + <dt><code>count</code></dt> + <dd>介于 <code>0</code> 和 {{jsxref("Global_Objects/Number/POSITIVE_INFINITY", "+Infinity")}} 之间的整数。表示在新构造的字符串中重复了多少遍原字符串。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p> 包含指定字符串的指定数量副本的新字符串。</p> + +<h3 id="Exceptions">Exceptions</h3> + +<ul> + <li>{{jsxref("Errors/Negative_repetition_count", "RangeError")}}: 重复次数不能为负数。</li> + <li>{{jsxref("Errors/Resulting_string_too_large", "RangeError")}}: 重复次数必须小于 infinity,且长度不会大于最长的字符串。</li> +</ul> + +<h2 id="兼容补丁Polyfill">兼容补丁(Polyfill)</h2> + +<p>此方法已添加到 ECMAScript 2015 规范中,并且可能尚未在所有 JavaScript 实现中可用。然而,你可以使用以下代码段对 String.prototype.repeat() 进行填充:</p> + +<pre class="brush: js language-js notranslate"><code class="language-js"><span class="keyword token">if</span> <span class="punctuation token">(</span><span class="operator token">!</span>String<span class="punctuation token">.</span>prototype<span class="punctuation token">.</span>repeat<span class="punctuation token">)</span> <span class="punctuation token">{</span> + String<span class="punctuation token">.</span>prototype<span class="punctuation token">.</span>repeat <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span>count<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="string token">'use strict'</span><span class="punctuation token">;</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span><span class="keyword token">this</span> <span class="operator token">==</span> <span class="keyword token">null</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">throw</span> <span class="keyword token">new</span> <span class="class-name token">TypeError</span><span class="punctuation token">(</span><span class="string token">'can\'t convert '</span> <span class="operator token">+</span> <span class="keyword token">this</span> <span class="operator token">+</span> <span class="string token">' to object'</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + <span class="keyword token">var</span> str <span class="operator token">=</span> <span class="string token">''</span> <span class="operator token">+</span> <span class="keyword token">this</span><span class="punctuation token">;</span> + count <span class="operator token">=</span> <span class="operator token">+</span>count<span class="punctuation token">;</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span>count <span class="operator token">!</span><span class="operator token">=</span> count<span class="punctuation token">)</span> <span class="punctuation token">{</span> + count <span class="operator token">=</span> <span class="number token">0</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span>count <span class="operator token"><</span> <span class="number token">0</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">throw</span> <span class="keyword token">new</span> <span class="class-name token">RangeError</span><span class="punctuation token">(</span><span class="string token">'repeat count must be non-negative'</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span>count <span class="operator token">==</span> <span class="number token">Infinity</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">throw</span> <span class="keyword token">new</span> <span class="class-name token">RangeError</span><span class="punctuation token">(</span><span class="string token">'repeat count must be less than infinity'</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + count <span class="operator token">=</span> Math<span class="punctuation token">.</span><span class="function token">floor<span class="punctuation token">(</span></span>count<span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span>str<span class="punctuation token">.</span>length <span class="operator token">==</span> <span class="number token">0</span> <span class="operator token">||</span> count <span class="operator token">==</span> <span class="number token">0</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">return</span> <span class="string token">''</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + <span class="comment token"> // 确保 count 是一个 31 位的整数。这样我们就可以使用如下优化的算法。 + // 当前(2014年8月),绝大多数浏览器都不能支持 1 << 28 长的字符串,所以:</span><span class="comment token"> +</span> <span class="keyword token">if</span> <span class="punctuation token">(</span>str<span class="punctuation token">.</span>length <span class="operator token">*</span> count <span class="operator token">>=</span> <span class="number token">1</span> <span class="operator token"><</span><span class="operator token"><</span> <span class="number token">28</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">throw</span> <span class="keyword token">new</span> <span class="class-name token">RangeError</span><span class="punctuation token">(</span><span class="string token">'repeat count must not overflow maximum string size'</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + <span class="keyword token">var</span> rpt <span class="operator token">=</span> <span class="string token">''</span><span class="punctuation token">;</span> + <span class="keyword token">for</span> <span class="punctuation token">(</span><span class="punctuation token">;</span><span class="punctuation token">;</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span><span class="punctuation token">(</span>count <span class="operator token">&</span> <span class="number token">1</span><span class="punctuation token">)</span> <span class="operator token">==</span> <span class="number token">1</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + rpt <span class="operator token">+</span><span class="operator token">=</span> str<span class="punctuation token">;</span> + <span class="punctuation token">}</span> + count <span class="operator token">></span><span class="operator token">></span><span class="operator token">>=</span> <span class="number token">1</span><span class="punctuation token">;</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span>count <span class="operator token">==</span> <span class="number token">0</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">break</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + str <span class="operator token">+</span><span class="operator token">=</span> str<span class="punctuation token">;</span> + <span class="punctuation token">}</span> + <span class="keyword token">return</span> rpt<span class="punctuation token">;</span> + <span class="punctuation token">}</span> +<span class="punctuation token">}</span></code></pre> + + +<h2 id="Examples" name="Examples">示例</h2> + +<pre class="brush:js notranslate"><span class="difflineplus">"abc".repeat(-1) // </span>RangeError: repeat count must be positive and less than inifinity +<span class="difflineplus">"abc".repeat(0) // ""</span> +<span class="difflineplus">"abc".repeat(1) // "abc"</span> +<span class="difflineplus">"abc".repeat(2) // "</span>abcabc<span class="difflineplus">" +</span>"abc".repeat(3.5)<span class="difflineplus"> // "abcabcabc" 参数count将会被自动转换成整数. +</span><span class="difflineplus">"abc".repeat(1/0) //</span> RangeError: repeat count must be positive and less than inifinity + +<span class="difflineplus">({toString : () => "abc", repeat : String.prototype.repeat}</span><span class="difflineplus">).repeat(2) +</span><span class="difflineplus">//"</span>abcabc<span class="difflineplus">",repeat是一个通用方法</span>,也就是它的调用者可以不是一个字符串对象.</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">规范</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.repeat', 'String.prototype.repeat')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">浏览器兼容性</h2> + +<p>{{Compat("javascript.builtins.String.repeat")}}</p> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("String.prototype.concat()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><strong><code>replace()</code></strong> 方法返回一个由替换值(<code>replacement</code>)替换部分或所有的模式(<code>pattern</code>)匹配项后的新字符串。模式可以是一个字符串或者一个<a href="/zh-CN/docs/Web/JavaScript/Reference/RegExp">正则表达式</a>,替换值可以是一个字符串或者一个每次匹配都要调用的回调函数。<strong>如果<code>pattern</code>是字符串,则仅替换第一个匹配项。</strong></p> + +<p>原字符串不会改变。</p> + +<div>{{EmbedInteractiveExample("pages/js/string-replace.html")}}</div> + + + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox notranslate"><code><var>str</var>.replace(<var>regexp</var>|<var>substr</var>, <var>newSubStr</var>|<var>function</var>)</code></pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>regexp </code>(pattern)</dt> + <dd>一个{{jsxref("RegExp")}} 对象或者其字面量。该正则所匹配的内容会被第二个参数的返回值替换掉。</dd> +</dl> + +<dl> + <dt><code>substr </code>(pattern)</dt> + <dd>一个将被 <code>newSubStr</code> 替换的 {{jsxref("String","字符串")}}。其被视为一整个字符串,而不是一个正则表达式。仅第一个匹配项会被替换。</dd> +</dl> + +<dl> + <dt><code>newSubStr</code> (replacement)</dt> + <dd>用于替换掉第一个参数在原字符串中的匹配部分的{{jsxref("String", "字符串")}}。该字符串中可以内插一些特殊的变量名。参考下面的<a href="#使用字符串作为参数">使用字符串作为参数</a>。</dd> +</dl> + +<dl> + <dt><code>function</code> (replacement)</dt> + <dd>一个用来创建新子字符串的函数,该函数的返回值将替换掉第一个参数匹配到的结果。参考下面的<a href="#指定一个函数作为参数">指定一个函数作为参数</a>。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>一个部分或全部匹配由替代模式所取代的新的字符串。</p> + +<h2 id="描述">描述</h2> + +<p>该方法并不改变调用它的字符串本身,而只是返回一个新的替换后的字符串。</p> + +<p>在进行全局的搜索替换时,正则表达式需包含 <code>g</code> 标志。</p> + +<h3 id="使用字符串作为参数">使用字符串作为参数</h3> + +<p>替换字符串可以插入下面的特殊变量名:</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <td class="header">变量名</td> + <td class="header">代表的值</td> + </tr> + <tr> + <td><code>$$</code></td> + <td>插入一个 "$"。</td> + </tr> + <tr> + <td><code>$&</code></td> + <td>插入匹配的子串。</td> + </tr> + <tr> + <td><code>$`</code></td> + <td>插入当前匹配的子串左边的内容。</td> + </tr> + <tr> + <td><code>$'</code></td> + <td>插入当前匹配的子串右边的内容。</td> + </tr> + <tr> + <td style="white-space: nowrap;"><code>$<em>n</em></code></td> + <td> + <p>假如第一个参数是 {{jsxref("RegExp")}}对象,并且 n 是个小于100的非负整数,那么插入第 n 个括号匹配的字符串。提示:索引是从1开始。如果不存在第 n个分组,那么将会把匹配到到内容替换为字面量。比如不存在第3个分组,就会用“$3”替换匹配到的内容。</p> + </td> + </tr> + <tr> + <td style="white-space: nowrap;"><code><em>$<Name></em></code></td> + <td> 这里<em><code>Name</code></em> 是一个分组名称。如果在正则表达式中并不存在分组(或者没有匹配),这个变量将被处理为空字符串。只有在支持命名分组捕获的浏览器中才能使用。</td> + </tr> + </tbody> +</table> + +<h3 id="指定一个函数作为参数">指定一个函数作为参数</h3> + +<p>你可以指定一个函数作为第二个参数。在这种情况下,当匹配执行后,该函数就会执行。 函数的返回值作为替换字符串。 (注意:上面提到的特殊替换参数在这里不能被使用。) 另外要注意的是,如果第一个参数是正则表达式,并且其为全局匹配模式,那么这个方法将被多次调用,每次匹配都会被调用。</p> + +<p>下面是该函数的参数:</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <td class="header">变量名</td> + <td class="header">代表的值</td> + </tr> + <tr> + <td><code>match</code></td> + <td>匹配的子串。(对应于上述的$&。)</td> + </tr> + <tr> + <td><code>p1,p2, ...</code></td> + <td> + <p>假如replace()方法的第一个参数是一个{{jsxref("RegExp")}} 对象,则代表第n个括号匹配的字符串。(对应于上述的$1,$2等。)例如,如果是用 <code>/(\a+)(\b+)/</code> 这个来匹配,<code>p1</code> 就是匹配的 <code>\a+</code>,<code>p2</code> 就是匹配的 <code>\b+</code>。</p> + </td> + </tr> + <tr> + <td><code>offset</code></td> + <td> + <p>匹配到的子字符串在原字符串中的偏移量。(比如,如果原字符串是 <code>'abcd'</code>,匹配到的子字符串是 <code>'bc'</code>,那么这个参数将会是 1)</p> + </td> + </tr> + <tr> + <td><code>string</code></td> + <td>被匹配的原字符串。</td> + </tr> + <tr> + <td>NamedCaptureGroup</td> + <td>命名捕获组匹配的对象</td> + </tr> + </tbody> +</table> + +<p>(精确的参数个数依赖于 <code>replace()</code> 的第一个参数是否是一个正则表达式({{jsxref("RegExp")}})对象,以及这个正则表达式中指定了多少个括号子串,如果这个正则表达式里使用了命名捕获, 还会添加一个命名捕获的对象)</p> + +<p>下面的例子将会使 <code>newString</code> 变成 <code>'abc - 12345 - #$*%'</code>:</p> + +<pre class="brush: js notranslate">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 - #$*% +</pre> + +<h2 id="Examples" name="Examples">示例</h2> + +<h3 id="在_replace_中使用正则表达式">在 <code>replace()</code> 中使用正则表达式</h3> + +<p>在下面的例子中,<code>replace()</code> 中使用了正则表达式及忽略大小写标示。</p> + +<pre class="brush: js notranslate">var str = 'Twas the night before Xmas...'; +var newstr = str.replace(/xmas/i, 'Christmas'); +console.log(newstr); // Twas the night before Christmas... +</pre> + +<h3 id="在_replace_中使用_global_和_ignore_选项">在 <code>replace()</code> 中使用 <code>global</code> 和 <code>ignore</code> 选项</h3> + +<p>下面的例子中,正则表达式包含有全局替换(g)和忽略大小写(i)的选项,这使得replace方法用'oranges'替换掉了所有出现的"apples".</p> + +<pre class="brush: js notranslate">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); +</pre> + +<h3 id="交换字符串中的两个单词">交换字符串中的两个单词</h3> + +<p>下面的例子演示了如何交换一个字符串中两个单词的位置,这个脚本使用$1 和 $2 代替替换文本。</p> + +<pre class="brush: js notranslate">var re = /(\w+)\s(\w+)/; +var str = "John Smith"; +var newstr = str.replace(re, "$2, $1"); +// Smith, John +console.log(newstr); +</pre> + +<h3 id="使用行内函数来修改匹配到的字符。">使用行内函数来修改匹配到的字符。</h3> + +<p>在这个例子中,所有出现的大写字母转换为小写,并且在匹配位置前加一个连字符。重要的是,在返回一个替换了的字符串前,在匹配元素前进行添加操作是必要的。</p> + +<p>在返回前,替换函数允许匹配片段作为参数,并且将它和连字符进行连接作为新的片段。</p> + +<pre class="brush: js notranslate">function styleHyphenFormat(propertyName) { + function upperToHyphenLower(match) { + return '-' + match.toLowerCase(); + } + return propertyName.replace(/[A-Z]/g, upperToHyphenLower); +} +</pre> + +<p>运行 <code>styleHyphenFormat('borderTop')</code><code>,</code><span>将</span><span>返回 'border-top'。</span></p> + +<p>因为我们想在最终的替换中进一步转变匹配结果,所以我们必须使用一个函数。这迫使我们在使用{{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}}方法前进行评估。如果我们尝试不用一个函数进行匹配,那么使用{{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} 方法将不会有效。</p> + +<pre class="brush: js notranslate">var newString = propertyName.replace(/[A-Z]/g, '-' + '$&'.toLowerCase()); // won't work +</pre> + +<p>这是因为 <code>'$&'.toLowerCase()</code> 会先被解析成字符串字面量(这会导致相同的'$&')而不是当作一个模式。</p> + +<h3 id="将华氏温度转换为对等的摄氏温度">将华氏温度转换为对等的摄氏温度</h3> + +<p>下面的例子演示如何将华氏温度转换为对等的摄氏温度。华氏温度用一个数字加一个"F"来表示,这个函数将返回一个数字加"C"来表示的摄氏温度。例如,如果输入是 212F,这个函数将返回 100C。如果输入的数字是 0F,这个方法将返回 "-17.77777777777778C"。</p> + +<p>正则表达式test检查任何数字是否以 F 结尾。华氏温度通过第二个参数p1进入函数。这个函数基于华氏温度作为字符串传递给f2c函数设置成摄氏温度。然后f2c()返回摄氏温度。这个函数与Perl的 s///e 标志相似。</p> + +<pre class="brush: js notranslate">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); +} +</pre> + +<h3 id="使用行内函数和正则来避免循环">使用行内函数和正则来避免循环</h3> + +<p>下例把某种模式的字符串转换为一个对象数组(其元素为对象)。</p> + +<p><strong>输入:</strong><br> + 一个由 x,- 和 _ 组成的字符串。</p> + +<pre class="notranslate">x-x_ + +---x---x---x--- + +-xxx-xx-x- + +_x_x___x___x___ +</pre> + +<p><strong>输出:</strong></p> + +<p>一个数组对象。'x' 产生一个 'on' 状态,'-'(连接符)产生一个 'off' 状态,而 '_' (下划线)表示 'on' 状态的长度。</p> + +<pre class="brush: js notranslate">[ + { on: true, length: 1 }, + { on: false, length: 1 }, + { on: true, length: 2 } + ... +]</pre> + +<p>代码片段:</p> + +<pre class="brush: js notranslate">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);</pre> + +<p>该代码片段生成了一个数组,包含三个期望格式的对象,避免了使用 for 循环语句。</p> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.11', 'String.prototype.replace')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.replace', 'String.prototype.replace')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.replace', 'String.prototype.replace')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.replace")}}</p> + +<h3 id="Firefox_备注">Firefox 备注</h3> + +<ul> + <li><code>flags</code> 是一个仅在 Gecko 中可用的非标准的第三方参数:<code><var>str</var>.replace(<var>regexp</var>|<var>substr</var>, <var>newSubStr</var>|<var>function, flags</var>)</code></li> + <li>从 Gecko 27 {{geckoRelease(27)}} 开始,这个方法就被整合到了ECMAScript规范中。当 replace() 被使用全局 g 标志的正则表达式调用时,{{jsxref("RegExp.lastIndex")}} 属性将被重置为 0({{bug(501739)}})。</li> + <li>从 Gecko 39 {{geckoRelease(39)}} 开始,<code>flags</code> 参数便被弃用,且在调用时会抛出一个控制台警告({{bug(1142351)}})。</li> + <li>从 Gecko 47 {{geckoRelease(47)}} 开始,在非发行版本中已不再支持非标准的 <code>flags</code> 参数,并且不久后会完全移除该参数({{bug(1245801)}})。</li> + <li>从 Gecko 49 {{geckoRelease(49)}} 开始,不再支持非标准的 <code>flags</code> 参数({{bug(1108382)}})。</li> +</ul> + +<h2 id="参见">参见</h2> + +<ul> + <li>{{jsxref("String.prototype.match()")}}</li> + <li>{{jsxref("RegExp.prototype.exec()")}}</li> + <li>{{jsxref("RegExp.prototype.test()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><strong><code>replaceAll()</code></strong> 方法返回一个新字符串,新字符串所有满足 <code>pattern</code> 的部分都已被<code>replacement</code> 替换。</span><span class="seoSummary"><code>pattern</code></span>可以是一个字符串或一个 {{jsxref("RegExp")}}, <code>replacement</code>可以是一个字符串或一个在每次匹配被调用的函数。</p> + +<p>原始字符串保持不变。</p> + +<div>{{EmbedInteractiveExample("pages/js/string-replaceall.html")}}</div> + + + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox notranslate">const newStr = <var>str</var>.replaceAll(<var>regexp</var>|<var>substr</var>, <var>newSubstr</var>|<var>function</var>)</pre> + +<div class="blockIndicator note"> +<p>当使用一个 `regex`时,您必须设置全局(“ g”)标志,<br> + 否则,它将引发 <code>TypeError</code>:“必须使用全局 RegExp 调用 replaceAll”。</p> +</div> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code><var>regexp</var></code> (pattern)</dt> + <dd>A {{jsxref("RegExp")}} object or literal with the global flag. The matches are replaced with <code><var>newSubstr</var></code> or the value returned by the specified <code><var>function</var></code>. A RegExp without the global ("g") flag will throw a <code>TypeError</code>: "replaceAll must be called with a global RegExp".</dd> + <dt><code><var>substr</var></code></dt> + <dd>A {{jsxref("String")}} that is to be replaced by <code><var>newSubstr</var></code>. It is treated as a literal string and is <em>not</em> interpreted as a regular expression.</dd> + <dt><code><var>newSubstr</var></code> (replacement)</dt> + <dd>The {{jsxref("String")}} that replaces the substring specified by the specified <code><var>regexp</var></code> or <code><var>substr</var></code> parameter. A number of special replacement patterns are supported; see the "<a href="#Specifying_a_string_as_a_parameter">Specifying a string as a parameter</a>" section below.</dd> + <dt><code><var>function</var></code> (replacement)</dt> + <dd>A function to be invoked to create the new substring to be used to replace the matches to the given <code><var>regexp</var></code> or <code><var>substr</var></code>. The arguments supplied to this function are described in the "<a href="#Specifying_a_function_as_a_parameter">Specifying a function as a parameter</a>" section below.</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>A new string, with all matches of a pattern replaced by a replacement.</p> + +<h2 id="描述">描述</h2> + +<p>此方法不会更改调用 {{jsxref("String")}} 对象。它只是返回一个新字符串。</p> + +<h3 id="将一个字符串作为一个参数">将一个字符串作为一个参数</h3> + +<p>The replacement string can include the following special replacement patterns:</p> + +<table class="standard-table"> + <thead> + <tr> + <th class="header" scope="col">Pattern</th> + <th class="header" scope="col">Inserts</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>$$</code></td> + <td>Inserts a <code>"$"</code>.</td> + </tr> + <tr> + <td><code>$&</code></td> + <td>Inserts the matched substring.</td> + </tr> + <tr> + <td><code>$`</code></td> + <td>Inserts the portion of the string that precedes the matched substring.</td> + </tr> + <tr> + <td><code>$'</code></td> + <td>Inserts the portion of the string that follows the matched substring.</td> + </tr> + <tr> + <td><code>$<var>n</var></code></td> + <td>Where <code><var>n</var></code> is a positive integer less than 100, inserts the <code><var>n</var></code>th parenthesized submatch string, provided the first argument was a {{jsxref("RegExp")}} object. Note that this is <code>1</code>-indexed.</td> + </tr> + </tbody> +</table> + +<h3 id="将一个函数指定为一个参数">将一个函数指定为一个参数</h3> + +<p>你可以指定一个函数作为第二个参数,在这种情况下,函数只有在匹配发生之后才会被调用。The function's result (return value) will be used as the replacement string. (<strong>Note:</strong> The above-mentioned special replacement patterns do <em>not</em> apply in this case.)</p> + +<p>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.</p> + +<p>The arguments to the function are as follows:</p> + +<table class="standard-table"> + <thead> + <tr> + <th class="header" scope="col">Possible name</th> + <th class="header" scope="col">Supplied value</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>match</code></td> + <td>The matched substring. (Corresponds to <code>$&</code> above.)</td> + </tr> + <tr> + <td><code>p1, p2, ...</code></td> + <td>The <var>n</var>th string found by a parenthesized capture group, provided the first argument to <code>replace()</code> was a {{jsxref("RegExp")}} object. (Corresponds to <code>$1</code>, <code>$2</code>, etc. above.) For example, if <code>/(\a+)(\b+)/</code>, was given, <code>p1</code> is the match for <code>\a+</code>, and <code>p2</code> for <code>\b+</code>.</td> + </tr> + <tr> + <td><code>offset</code></td> + <td>The offset of the matched substring within the whole string being examined. (For example, if the whole string was <code>'abcd'</code>, and the matched substring was <code>'bc'</code>, then this argument will be <code>1</code>.)</td> + </tr> + <tr> + <td><code>string</code></td> + <td>The whole string being examined.</td> + </tr> + </tbody> +</table> + +<p>(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.)</p> + +<h2 id="例子">例子</h2> + +<h3 id="使用_replaceAll">使用 replaceAll</h3> + +<pre class="brush: js notranslate">'aabbcc'.replaceAll('b', '.'); +// 'aa..cc'</pre> + +<h3 id="非全局_regex_抛出">非全局 regex 抛出</h3> + +<p>使用正则表达式搜索值时,它必须是全局的。这将行不通:</p> + +<pre class="brush: js; example-bad notranslate">'aabbcc'.replaceAll(/b/, '.'); +TypeError: replaceAll must be called with a global RegExp +</pre> + +<p>这将可以正常运行:</p> + +<pre class="brush: js; example-good notranslate">'aabbcc'.replaceAll(/b/g, '.'); +"aa..cc" +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.replaceall', 'String.prototype.replaceAll')}}</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.replaceAll")}}</p> + +<h2 id="了解更多">了解更多</h2> + +<ul> + <li>{{jsxref("String.prototype.replace", "String.prototype.replace()")}}</li> + <li>{{jsxref("String.prototype.match", "String.prototype.match()")}}</li> + <li>{{jsxref("RegExp.prototype.exec", "RegExp.prototype.exec()")}}</li> + <li>{{jsxref("RegExp.prototype.test", "RegExp.prototype.test()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><strong><code>search()</code></strong> 方法执行正则表达式和 {{jsxref("String")}} 对象之间的一个搜索匹配。</p> + +<div>{{EmbedInteractiveExample("pages/js/string-search.html")}}</div> + + + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox notranslate"><var>str</var>.search(<var>regexp</var>)</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>regexp</code></dt> + <dd>一个{{jsxref("RegExp", "正则表达式(regular expression)")}}对象</dd> + <dd>如果传入一个非正则表达式对象 <code>regexp</code>,则会使用 <code>new RegExp(regexp)</code> 隐式地将其转换为正则表达式对象。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>如果匹配成功,则 <code>search()</code> 返回正则表达式在字符串中首次匹配项的索引;否则,返回 <code>-1</code>。</p> + +<h2 id="描述">描述</h2> + +<p>当你想要知道字符串中是否存在某个模式(pattern)时可使用 <code>search()</code>,类似于正则表达式的 {{jsxref("RegExp.test", "test()")}} 方法。当要了解更多匹配信息时,可使用 {{jsxref("String.match", "match()")}}(但会更慢一些),该方法类似于正则表达式的 {{jsxref("RegExp.exec", "exec()")}} 方法。</p> + +<h2 id="示例">示例</h2> + +<h3 id="例子:使用_search">例子:使用 <code>search()</code></h3> + +<p>下面的例子中用两个不同的正则表达式对同一个字符串执行搜索匹配,得到一个成功匹配(正数返回值)和一个失败匹配(-1)。</p> + +<pre class="brush: js notranslate">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</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.search', 'String.prototype.search')}}</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.search")}}</p> + +<h2 id="Gecko_注意事项">Gecko 注意事项</h2> + +<ul> + <li>在 {{Gecko("8.0")}} 及之前的版本,<code>search()</code> 的实现有问题:在调用该方法时,若不传递参数或者参数为 {{jsxref("undefined")}},该方法将不会匹配空字符串,而是匹配字符串 "undefined"。这个问题已被修复,现在,<code>"a".search()</code> 和 <code>"a".search(undefined)</code> 都能正确返回 0。</li> + <li>Starting with Gecko 39 {{geckoRelease(39)}}, the non-standard <code>flags</code> argument is deprecated and throws a console warning ({{bug(1142351)}}).</li> + <li>Starting with Gecko 47 {{geckoRelease(47)}}, the non-standard <code>flags</code> argument is no longer supported in non-release builds and will soon be removed entirely ({{bug(1245801)}}).</li> + <li>Starting with Gecko 49 {{geckoRelease(49)}}, the non-standard <code>flags</code> argument is no longer supported ({{bug(1108382)}}).</li> +</ul> + +<h2 id="参见">参见</h2> + +<ul> +<li><a href="/zh-CN/docs/Web/JavaScript/Guide/Regular_Expressions">在 JavaScript 中使用正则表达式</a></li> + <li>{{jsxref("String.prototype.match()")}}</li> + <li>{{jsxref("RegExp.prototype.exec()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><strong><code>slice()</code></strong> 方法提取某个字符串的一部分,并返回一个新的字符串,且不会改动原字符串。</p> + +<div>{{EmbedInteractiveExample("pages/js/string-slice.html")}}</div> + + + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><var>str</var>.slice(<var>beginIndex</var>[, <var>endIndex</var>])</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>beginIndex</code></dt> + <dd>从该索引(以 0 为基数)处开始提取原字符串中的字符。如果值为负数,会被当做 <code>strLength + beginIndex</code> 看待,这里的<code>strLength</code> 是字符串的长度(例如, 如果 <code>beginIndex</code> 是 -3 则看作是:<code>strLength - 3</code>)</dd> + <dt><code>endIndex</code></dt> + <dd>可选。在该索引(以 0 为基数)处结束提取字符串。如果省略该参数,<code style="font-style: normal;">slice()</code> 会一直提取到字符串末尾。<span style="line-height: 1.5;">如果该参数为负数,则被看作是 strLength + endIndex,这里的 strLength 就是字符串的长度(例如,如果 endIndex 是 -3,则是, strLength - 3)。</span></dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>返回一个从原字符串中提取出来的新字符串</p> + +<h2 id="描述">描述</h2> + +<p><code>slice()</code> 从一个字符串中提取字符串并返回新字符串。在一个字符串中的改变不会影响另一个字符串。也就是说,<code>slice</code> 不会修改原字符串(只会返回一个包含了原字符串中部分字符的新字符串)。</p> + +<p><code>slice()</code> 提取的新字符串包括<code>beginIndex</code>但不包括 <code>endIndex</code>。下面有两个例子。</p> + +<p>例 1:<code>str.slice(1, 4)</code> 提取第二个字符到第四个字符(被提取字符的索引值(index)依次为 1、2,和 3)。</p> + +<p>例 2:<code>str.slice(2, -1)</code> 提取第三个字符到倒数第一个字符。</p> + +<h2 id="Examples" name="Examples" style="margin-bottom: 20px; font-size: 2.14285714285714rem;">例子</h2> + +<h3 id="使用_slice()_创建一个新的字符串">使用 <code>slice()</code> 创建一个新的字符串</h3> + +<p>下面例子使用 <code>slice()</code> 创建了一个新字符串。</p> + +<pre class="brush: js">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); // 输出:"" +</pre> + +<h3 id="给_slice()_传入负值索引">给 <code>slice()</code> 传入负值索引</h3> + +<p>下面的例子在使用 <code>slice()</code> 时传入了负值作为索引。</p> + +<pre class="brush: js">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' +</pre> + +<h2 id="规范" style="margin-bottom: 20px; font-size: 2.14285714285714rem;">规范</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.slice', 'String.prototype.slice')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.slice', 'String.prototype.slice')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.13', 'String.prototype.slice')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + + + +<p>{{Compat("javascript.builtins.String.slice")}}</p> + +<h2 id="参见">参见</h2> + +<ul> + <li>{{jsxref("String.prototype.substr()")}} {{deprecated_inline}}</li> + <li>{{jsxref("String.prototype.substring()")}}</li> + <li>{{jsxref("Array.prototype.slice()")}}</li> +</ul> 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 +--- +<div>{{JSRef}} {{deprecated_header}}</div> + +<p><strong><code>small()</code></strong> 方法的作用是创建一个使字符串显示小号字体的 {{HTMLElement("small")}} 标签。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code><var>str</var>.small()</code></pre> + +<h3 id="返回值">返回值</h3> + +<p>带有 {{HTMLElement("small")}} 标签的字符串。</p> + +<h2 id="描述">描述</h2> + +<p><code>small()</code> 方法会 将一个字符串嵌入到<code><small></code> 标签中: <code>"<small>str</small>"。</code></p> + +<h2 id="示例">示例</h2> + +<h3 id="使用small()函数"><code>使用small()函数</code></h3> + +<p>为了改变一个字符串的字体大小,下面的例子使用了字符串中的方法:</p> + +<pre class="brush: js">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> +</pre> + +<p>使用{{domxref("HTMLElement.style", "element.style")}}对象,你能更加一般地获得和操作该元素的属性,比如:</p> + +<pre class="brush: js">document.getElementById('yourElemId').style.fontSize = '0.7em'; +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.small', 'String.prototype.small')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>初始定义。 在JavaScript 1.0中实现。在(规范性)附件B中定义了用于Web浏览器的附加ECMAScript 特性。</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.small', 'String.prototype.small')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>在(规范性)附件B中定义了用于Web浏览器的附加ECMAScript 特性。</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("String.prototype.fontsize()")}}</li> + <li>{{jsxref("String.prototype.big()")}}</li> +</ul> 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 +--- +<p>{{JSRef}}</p> + +<p><code><strong>split() </strong></code>方法使用指定的分隔符字符串将一个{{jsxref("String")}}对象分割成子字符串数组,以一个指定的分割字串来决定每个拆分的位置。 </p> + +<div>{{EmbedInteractiveExample("pages/js/string-split.html")}}</div> + + + +<h2 id="Syntax" name="Syntax">语法</h2> + +<pre class="syntaxbox"><code><em>str.split([separator[, limit]])</em></code> +</pre> + +<div class="blockIndicator warning"> +<p>注意:如果使用空字符串(“)作为分隔符,则字符串不是在每个用户感知的字符(图形素集群)之间,也不是在每个Unicode字符(代码点)之间,而是在每个UTF-16代码单元之间。这会摧毁代理对。还请参见<a href="https://stackoverflow.com/questions/4547609/how-do-you-get-a-string-to-a-character-array-in-javascript/34717402#34717402">how do you get a string to a character array in javascript</a></p> +</div> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>separator</code></dt> + <dd>指定表示每个拆分应发生的点的字符串。<code>separator</code> 可以是一个字符串或<a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp" title="JavaScript/Reference/Global_Objects/RegExp">正则表达式</a>。 如果纯文本分隔符包含多个字符,则必须找到整个字符串来表示分割点。如果在str中省略或不出现分隔符,则返回的数组包含一个由整个字符串组成的元素。如果分隔符为空字符串,则将str原字符串中每个字符的数组形式返回。</dd> + <dt><code>limit</code></dt> + <dd>一个整数,限定返回的分割片段数量。当提供此参数时,split 方法会在指定分隔符的每次出现时分割该字符串,但在限制条目已放入数组时停止。如果在达到指定限制之前达到字符串的末尾,它可能仍然包含少于限制的条目。新数组中不返回剩下的文本。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>返回源字符串以分隔符出现位置分隔而成的一个 {{jsxref("Array")}} </p> + +<h2 id="Description" name="Description">描述</h2> + +<p>找到分隔符后,将其从字符串中删除,并将子字符串的数组返回。如果没有找到或者省略了分隔符,则该数组包含一个由整个字符串组成的元素。如果分隔符为空字符串,则将str转换为字符数组。如果分隔符出现在字符串的开始或结尾,或两者都分开,分别以空字符串开头,结尾或两者开始和结束。因此,如果字符串仅由一个分隔符实例组成,则该数组由两个空字符串组成。</p> + +<p>如果分隔符是包含捕获括号的正则表达式,则每次分隔符匹配时,捕获括号的结果(包括任何未定义的结果)将被拼接到输出数组中。但是,并不是所有浏览器都支持此功能。</p> + +<p>{{Note("当字符串为空时,split()返回一个包含一个空字符串的数组,而不是一个空数组,如果字符串和分隔符都是空字符串,则返回一个空数组。")}}</p> + +<h2 id="Examples" name="Examples">示例</h2> + +<h3 id="Example_Using_split" name="Example:_Using_split">使用 <code>split()</code></h3> + +<p>下例定义了一个函数:根据指定的分隔符将一个字符串分割成一个字符串数组。分隔字符串后,该函数依次输出原始字符串信息,被使用的分隔符,返回数组元素的个数,以及返回数组中所有的元素。</p> + +<pre class="brush: js">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); +</pre> + +<p>上例输出下面结果:</p> + +<pre>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 / +</pre> + +<h3 id="Example_Removing_spaces_from_a_string" name="Example:_Removing_spaces_from_a_string">移出字符串中的空格</h3> + +<p>下例中,<code>split()</code> 方法会查找“0 或多个空白符接着的分号,再接着 0 或多个空白符”模式的字符串,找到后,就将空白符从字符串中移除,<code>nameList</code> 是 <code>split</code> 的返回数组。</p> + +<pre class="brush: js">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); +</pre> + +<p>上例输出两行,第一行输出原始字符串,第二行输出结果数组。</p> + +<pre><code>Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand +[ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand", "" ]</code> +</pre> + +<h3 id="Example_Returning_a_limited_number_of_splits" name="Example:_Returning_a_limited_number_of_splits">限制返回值中分割元素数量</h3> + +<p>下例中,<code>split</code> 查找字符串中的 0 或多个空格,并返回找到的前 3 个分割元素(splits)。</p> + +<pre class="brush: js">var myString = "Hello World. How are you doing?"; +var splits = myString.split(" ", 3); + +console.log(splits); +</pre> + +<p>上例输出:</p> + +<pre><code>["Hello", "World.", "How"]</code></pre> + +<h3 id="Example_Capturing_parentheses" name="Example:_Capturing_parentheses">靠正则来分割使结果中包含分隔块</h3> + +<p>如果 <code>separator</code> 包含捕获括号(capturing parentheses),则其匹配结果将会包含在返回的数组中。</p> + +<pre class="brush: js">var myString = "Hello 1 word. Sentence number 2."; +var splits = myString.split(/(\d)/); + +console.log(splits); +</pre> + +<p>上例输出:</p> + +<pre><code>[ "Hello ", "1", " word. Sentence number ", "2", "." ]</code></pre> + +<h3 id="使用一个数组来作为分隔符">使用一个数组来作为分隔符</h3> + +<pre><code>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"]</code></pre> + +<h3 id="用split来颠倒字符串顺序">用split()来颠倒字符串顺序</h3> + +<div class="blockIndicator warning"> +<p>注意这并非一种很健壮的逆转字符串的方法:</p> + +<pre><code>const str = 'asdfghjkl'; +const strReverse = str.split('').reverse().join(''); // 'lkjhgfdsa' +// split() returns an array on which reverse() and join() can be applied</code></pre> + +<p>如果字符串包含图形素集群,即使使用Unicode感知的拆分(use for example <a href="https://github.com/mathiasbynens/esrever">esrever</a> instead),也不能工作。</p> + +<pre><code>const str = 'résumé'; +const strReverse = str.split(/(?:)/u).reverse().join(''); +// => "́emuśer"</code></pre> + +<p>Bonus: use {{jsxref("Operators/Comparison_Operators", "===", "#Identity_strict_equality_(===)")}} operator to test if the original string was palindrome.</p> +</div> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>ECMAScript 3rd Edition.</td> + <td>Standard</td> + <td>Initial definition.<br> + Implemented in JavaScript 1.1</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.14', 'String.prototype.split')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.split', 'String.prototype.split')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{Compat("javascript.builtins.String.split")}}</p> + +<h2 id="See_also" name="See_also">相关链接</h2> + +<ul> + <li>{{jsxref("String.prototype.charAt()")}}</li> + <li>{{jsxref("String.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> + <li>{{jsxref("Array.prototype.join()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><code><strong>startsWith()</strong></code> 方法用来判断当前字符串是否以另外一个给定的子字符串开头,并根据判断结果返回 <code>true</code> 或 <code>false</code>。</span></p> + +<div>{{EmbedInteractiveExample("pages/js/string-startswith.html")}}</div> + + + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox notranslate"><var>str</var>.startsWith(<var>searchString</var>[, <var>position</var>])</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>searchString</code></dt> + <dd>要搜索的子字符串。</dd> + <dt><code>position</code> {{optional_inline}}</dt> + <dd>在 <code>str</code> 中搜索 <code><var>searchString</var></code> 的开始位置,默认值为 0。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>如果在字符串的开头找到了给定的字符则返回<strong><code>true</code></strong>;否则返回<strong><code>false</code></strong>。</p> + +<h2 id="描述">描述</h2> + +<p>这个方法能够让你确定一个字符串是否以另一个字符串开头。这个方法区分大小写。</p> + +<h2 id="Polyfill">Polyfill</h2> + +<p>此方法已被添加至 ECMAScript 2015 规范之中,但可能不能在所有的现行 JavaScript 实现中使用。不过,你可以用以下的代码段为 <code>String.prototype.startsWith()</code> 制作 Polyfill:</p> + +<pre class="brush: js notranslate">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; + } + }); +} +</pre> + +<p>Mathias Bynens 在 Github 上提供了<a href="https://github.com/mathiasbynens/String.prototype.startsWith">一份更为稳定有效(完全符合 ES2015 规范),但性能略差、代码紧凑性微减的 PolyFill</a>。</p> + +<h2 id="示例">示例</h2> + +<h3 id="使用_startsWith">使用 <code>startsWith()</code></h3> + +<pre class="brush:js; notranslate">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</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.startsWith")}}</p> + +<h2 id="参见">参见</h2> + +<ul> + <li>{{jsxref("String.prototype.endsWith()")}}</li> + <li>{{jsxref("String.prototype.includes()")}}</li> + <li>{{jsxref("String.prototype.indexOf()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> +</ul> 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 +--- +<div>{{JSRef}} {{deprecated_header}}</div> + +<p><strong><code>strike()</code></strong>方法创建{{HTMLElement("strike")}} HTML 元素,使字符串展示为被删除的文本。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code><var>str</var>.strike()</code></pre> + +<h3 id="返回值">返回值</h3> + +<p>包含{{HTMLElement("strike")}} HTML 元素的字符串。</p> + +<h2 id="描述">描述</h2> + +<p><code>strike()</code>方法将字符串嵌入<code><strike></code>标签: <code>"<strike>str</strike>"</code>.</p> + +<h2 id="示例">示例</h2> + +<h3 id="使用strike()">使用<code>strike()</code></h3> + +<p>下面的示例使用字符串方法来修改字符串的格式:</p> + +<pre class="brush: js">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> +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.strike', 'String.prototype.strike')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>初始定义。在 JavaScript 1.0 中实现。 在(规范性)附件 B 中定义为用于 Web 浏览器的 ECMAScript 附加特性。</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.strike', 'String.prototype.strike')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>在(规范性)附件 B 中定义为用于 Web 浏览器的 ECMAScript 附加特性。</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="另见">另见</h2> + +<ul> + <li>{{jsxref("String.prototype.blink()")}}</li> + <li>{{jsxref("String.prototype.bold()")}}</li> + <li>{{jsxref("String.prototype.italics()")}}</li> +</ul> 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 +--- +<div>{{JSRef}} {{deprecated_header}}</div> + +<p><strong><code>sub()</code></strong>方法创建一个 {{HTMLElement("sub")}} HTML 元素,使字符串展示为下标。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code><var>str</var>.sub()</code></pre> + +<h3 id="返回值">返回值</h3> + +<p>包含{{HTMLElement("sub")}} HTML 元素的字符串。</p> + +<h2 id="描述">描述</h2> + +<p><code>sub()</code>方法将字符串嵌入<code><sub></code>标签: <code>"<sub>str</sub>"</code>.</p> + +<h2 id="示例">示例</h2> + +<h3 id="使用sub()和sup()方法">使用<code>sub()</code>和<code>sup()</code>方法</h3> + +<p>下面的示例使用了<code>sub()</code>和{{jsxref("String.prototype.sup()", "sup()")}}方法来格式化字符串:</p> + +<pre class="brush: js">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>的样子。 +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.sub', 'String.prototype.sub')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>初始定义。在 JavaScript 1.0 中实现。在(规范性)附件 B 中定义为用于 Web 浏览器的 ECMAScript 附加特性。</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.sub', 'String.prototype.sub')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>在(规范性)附件 B 中定义为用于 Web 浏览器的 ECMAScript 附加特性。</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="另见">另见</h2> + +<ul> + <li>{{jsxref("String.prototype.sup()")}}</li> +</ul> 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 +--- +<p>{{JSRef}}</p> + +<div class="warning">警告: 尽管 <code>String.prototype.substr(…)</code> 没有严格被废弃 (as in "removed from the Web standards"), 但它被认作是遗留的函数并且可以的话应该避免使用。它并非JavaScript核心语言的一部分,未来将可能会被移除掉。如果可以的话,使用 <code><a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/substring">substring()</a></code> 替代它.</div> + +<p><code><strong>substr()</strong></code> 方法返回一个字符串中从指定位置开始到指定字符数的字符。</p> + +<h2 id="Syntax" name="Syntax">语法</h2> + +<pre class="syntaxbox"><code><em>str</em>.substr(<em>start</em>[, <em>length</em>])</code></pre> + +<h3 id="Parameters" name="Parameters">参数</h3> + +<dl> + <dt><code>start</code></dt> + <dd>开始提取字符的位置。如果为负值,则被看作 <code style="font-style: normal; line-height: 1.5;">strLength + </code><code style="font-style: normal; line-height: 1.5;">start,其中</code><span style="line-height: 1.5;"> </span><code style="font-style: normal; line-height: 1.5;">strLength</code><span style="line-height: 1.5;"> 为字符串的长度(例如,如果 <code>start</code> 为 <code>-3,则被看作</code> <code>strLength + (-3))。</code></span></dd> +</dl> + +<dl> + <dt><code>length</code></dt> + <dd>可选。提取的字符数。</dd> +</dl> + +<h2 id="Description" name="Description">描述</h2> + +<p><code>start</code> 是一个字符的索引。首字符的索引为 0,最后一个字符的索引为 字符串的长度减去1。<code>substr</code> 从 <code>start</code> 位置开始提取字符,提取 <code>length</code> 个字符(或直到字符串的末尾)。</p> + +<p>如果 <code>start</code> 为正值,且大于或等于字符串的长度,则 <code>substr</code> 返回一个空字符串。</p> + +<p>如果 <code>start</code> 为负值,则 <code>substr</code> 把它作为从字符串末尾开始的一个字符索引。如果 <code>start</code> 为负值且 <code>abs(start)</code> 大于字符串的长度,则 <code>substr</code> 使用 0 作为开始提取的索引。注意负的 <code>start</code> 参数不被 Microsoft JScript 所支持。</p> + +<p>如果 <code>length</code> 为 0 或负值,则 <code>substr</code> 返回一个空字符串。如果忽略 <code>length</code>,则 <code>substr</code> 提取字符,直到字符串末尾。</p> + +<h2 id="示例">示例</h2> + +<h3 id="Example:_Using_substr" name="Example:_Using_substr">例子:使用 <code>substr</code></h3> + +<pre class="brush: js">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): +</pre> + +<h2 id="Description" name="Description">兼容旧环境(Polyfill)</h2> + +<p>Microsoft's JScript 不支持负的 start 索引。如果你想充分利用该方法的功能,则需要使用下面的兼容性代码修复此 bug:</p> + +<pre class="brush: js">// 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); +}</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>ECMAScript 3rd Edition.</td> + <td>Standard</td> + <td>Defined in the (informative) Compatibility Annex B.<br> + Implemented in JavaScript 1.0</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-B.2.3', 'String.prototype.substr')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Defined in the (informative) Compatibility Annex B</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.substr', 'String.prototype.substr')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<p><strong>Note</strong>: Up to version 3.6, Firefox had a bug which caused <code>substr</code> to return empty result when an explicit <code>undefined</code> value was passed in as the <code>length</code>.</p> + +<h2 id="See_also" name="See_also">相关链接</h2> + +<ul> + <li>{{jsxref("String.prototype.slice()")}}</li> + <li>{{jsxref("String.prototype.substring()")}}</li> +</ul> 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 +--- +<p>{{JSRef}}</p> + +<p><strong><code>substring() </code></strong>方法返回一个字符串在开始索引到结束索引之间的一个子集, 或从开始索引直到字符串的末尾的一个子集。</p> + +<h2 id="Syntax" name="Syntax">语法</h2> + +<pre class="syntaxbox notranslate"><code><var>str</var>.substring(<var>indexStart</var>[, <var>indexEnd</var>])</code></pre> + +<h3 id="Parameters" name="Parameters">参数</h3> + +<dl> + <dt><code>indexStart</code></dt> + <dd>需要截取的第一个字符的索引,该索引位置的字符作为返回的字符串的首字母。</dd> + <dt><code>indexEnd</code></dt> + <dd>可选。一个 0 到字符串长度之间的整数,以该数字为索引的字符不包含在截取的字符串内。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>包含给定字符串的指定部分的新字符串。</p> + +<h2 id="Description" name="Description">描述</h2> + +<p><code>substring</code> 提取从 <code>indexStart</code> 到 <code>indexEnd</code>(不包括)之间的字符。特别地:</p> + +<ul> + <li>如果 <code>indexStart</code> 等于 <code>indexEnd</code>,<code>substring</code> 返回一个空字符串。</li> + <li>如果省略 <code>indexEnd</code>,<code>substring</code> 提取字符一直到字符串末尾。</li> + <li>如果任一参数小于 0 或为 {{jsxref("NaN")}},则被当作 0。</li> + <li>如果任一参数大于 <code>stringName.length</code>,则被当作 <code>stringName.length</code>。</li> + <li>如果 <code>indexStart</code> 大于 <code>indexEnd</code>,则 <code>substring</code> 的执行效果就像两个参数调换了一样。见下面的例子。</li> +</ul> + +<h2 id="Examples" name="Examples">示例</h2> + +<h3 id="Example_Using_substring" name="Example:_Using_substring">例子:使用 <code>substring</code></h3> + +<p>下例使用 <code>substring</code> 输出字符串 "<code>Mozilla</code>" 中的字符:</p> + +<pre class="brush:js notranslate">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)); +</pre> + +<h3 id="运用_length_属性来使用_substring"><strong>运用 length 属性来使用 substring()</strong></h3> + +<p>下面一个例子运用了 String.length 属性去获取指定字符串的倒数元素。显然这个办法更容易记住,因为你不再像上面那个例子那样去记住起始位置和最终位置。</p> + +<pre class="brush: js notranslate"><code>// Displays 'illa' the last 4 characters +var anyString = 'Mozilla'; +var anyString4 = anyString.substring(anyString.length - 4); +console.log(anyString4);</code> + +// Displays 'zilla' the last 5 characters +var anyString = 'Mozilla'; +var anyString5 = anyString.substring(anyString.length - 5); +console.log(anyString5);</pre> + +<h3 id="Example_Replacing_a_substring_within_a_string" name="Example:_Replacing_a_substring_within_a_string">例子:替换一个字符串的子字符串</h3> + +<p>下例替换了一个字符串中的子字符串。可以替换单个字符和子字符串。该例结尾调用的函数将 "<code>Brave New World</code>" 变成了 "<code>Brave New Web</code>"。</p> + +<pre class="brush:js notranslate">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");</pre> + +<p>需要注意的是,如果 <code>oldS</code> 是 <code>newS</code> 的子字符串将会导致死循环。例如,尝试把 "Web" 替换成 "OtherWorld"。一个更好的方法如下:</p> + +<pre class="brush:js notranslate">function replaceString(oldS, newS,fullS){ + return fullS.split(oldS).join(newS); +}</pre> + +<p><span style="line-height: 1.5;">上面的代码只是子字符串操作的一个例子。如果你需要替换子字符串,更多时候会用到 </span><span style="line-height: 1.5em;">{{jsxref("String.prototype.replace()")}}。</span></p> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>ECMAScript 1st Edition.</td> + <td>Standard</td> + <td>Implemented in JavaScript 1.0</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.15', 'String.prototype.substring')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.substring', 'String.prototype.substring')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also" name="See_also">相关链接</h2> + +<ul> + <li>{{jsxref("String.prototype.substr()")}}</li> + <li>{{jsxref("String.prototype.slice()")}}</li> +</ul> 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 +--- +<div>{{JSRef}} {{deprecated_header}}</div> + +<p><strong><code>sup()</code></strong>方法创建 一个{{HTMLElement("sup")}}HTML 元素,使字符串显示为上标。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code><var>str</var>.sup()</code></pre> + +<h3 id="返回值">返回值</h3> + +<p>包含{{HTMLElement("sup")}} HTML 元素的字符串。</p> + +<h2 id="描述">描述</h2> + +<p><code>sup()</code> 方法将字符串嵌入 <code><sup></code> 标签中:<code>"<sup>str</sup>"</code>.</p> + +<h2 id="示例">示例</h2> + +<h3 id="使用sub()和sup()方法">使用<code>sub()</code>和<code>sup()</code>方法</h3> + +<p>下面的示例使用了{{jsxref("String.prototype.sub()", "sub()")}}和<code>sup()</code>方法来格式化字符串:</p> + +<pre class="brush: js">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>的样子。" +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.sup', 'String.prototype.sup')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>初始定义。在 JavaScript 1.0 中实现。在(规范性)附件 B 中定义为用于 Web 浏览器的 ECMAScript 附加特性。</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.sup', 'String.prototype.sup')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>在(规范性)附件 B 中定义为用于 Web 浏览器的 ECMAScript 附加特性。</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="另见">另见</h2> + +<ul> + <li>{{jsxref("String.prototype.sub()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><strong><code>toLocaleLowerCase()</code></strong>方法根据任何指定区域语言环境设置的大小写映射,返回调用字符串被转换为小写的格式。</p> + +<h2 id="语法">语法</h2> + +<pre><var>str</var>.toLocaleLowerCase() +<var>str</var>.toLocaleLowerCase(locale) +<var>str</var>.toLocaleLowerCase([locale, locale, ...])</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>locale</code> {{optional_inline}}</dt> + <dd>参数 <code>locale</code> 指明要转换成小写格式的特定语言区域。 如果以一个数组 {{jsxref("Array")}}形式给出多个locales, 最合适的地区将被选出来应用(参见<a href="https://tc39.github.io/ecma402/#sec-bestavailablelocale">best available locale</a>)。默认的locale是主机环境的当前区域(locale)设置。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>根据任何特定于语言环境的案例映射规则将被调用字串转换成小写格式的一个新字符串。</p> + +<h3 id="Exceptions">Exceptions</h3> + +<ul> + <li>A {{jsxref("RangeError")}} ("invalid language tag: xx_yy") is thrown if a <code>locale</code> argument isn't a valid language tag.</li> + <li>A {{jsxref("TypeError")}} ("invalid element in locales argument") is thrown if an array element isn't of type string.</li> +</ul> + +<h2 id="描述">描述</h2> + +<p><code>toLocaleLowerCase()</code> 方法返回根据任意区域语言大小写映射集而转换成小写格式的字符串。<code>toLocaleLowerCase()</code> 并不会影响字符串原本的值。在大多数情况下,该方法和调用 {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}}的结果相同,但是在某些区域环境中,比如土耳其语,它的大小写映射并不遵循在Unicode中的默认的大小写映射,因此会有一个不同的结果。</p> + +<h2 id="例子">例子</h2> + +<h3 id="使用toLocaleLowerCase"><code><font face="Open Sans, Arial, sans-serif">使用</font>toLocaleLowerCase()</code></h3> + +<pre><code>'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</code></pre> + +<h2 id="规范">规范</h2> + +<table> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.17', 'String.prototype.toLocaleLowerCase')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.tolocalelowercase', 'String.prototype.toLocaleLowerCase')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.tolocalelowercase', 'String.prototype.toLocaleLowerCase')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES Int Draft', '#sup-string.prototype.tolocalelowercase', 'String.prototype.toLocaleLowerCase')}}</td> + <td>{{Spec2('ES Int Draft')}}</td> + <td>ES Intl 2017 added the <code>locale</code>parameter.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="参阅">参阅</h2> + +<ul> + <li>{{jsxref("String.prototype.toLocaleUpperCase()")}}</li> + <li>{{jsxref("String.prototype.toLowerCase()")}}</li> + <li>{{jsxref("String.prototype.toUpperCase()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><strong><code>toLocaleUpperCase()</code></strong> 方法根据本地主机语言环境把字符串转换为大写格式,并返回转换后的字符串。</p> + +<div>{{EmbedInteractiveExample("pages/js/string-tolocaleuppercase.html")}}</div> + + + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><var>str</var>.toLocaleUpperCase() +<var>str</var>.toLocaleUpperCase(locale) +<var>str</var>.toLocaleUpperCase([locale, locale, ...]) +</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>locale</code> {{optional_inline}}</dt> + <dd>The <code>locale</code> 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 <a href="https://tc39.github.io/ecma402/#sec-bestavailablelocale">best available locale</a> is used. The default locale is the host environment’s current locale.</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>A new string representing the calling string converted to upper case, according to any locale-specific case mappings.</p> + +<h3 id="Exceptions">Exceptions</h3> + +<ul> + <li>A {{jsxref("RangeError")}} ("invalid language tag: xx_yy") is thrown if a <code>locale</code> argument isn't a valid language tag.</li> + <li>A {{jsxref("TypeError")}} ("invalid element in locales argument") is thrown if an array element isn't of type string.</li> +</ul> + +<h2 id="描述">描述</h2> + +<p>The <code>toLocaleUpperCase()</code> method returns the value of the string converted to upper case according to any locale-specific case mappings. <code>toLocaleUpperCase()</code> 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.</p> + +<p>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 <code>false</code>:<br> + <code>x.toLocaleLowerCase() === x.toLocaleUpperCase().toLocaleLowerCase()</code></p> + +<h2 id="例子">例子</h2> + +<h3 id="使用_toLocaleUpperCase">使用 <code>toLocaleUpperCase()</code></h3> + +<pre class="brush: js">'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'</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.tolocaleuppercase', 'String.prototype.toLocaleUpperCase')}}</td> + </tr> + <tr> + <td>{{SpecName('ES Int Draft', '#sup-string.prototype.tolocaleuppercase', 'String.prototype.toLocaleUpperCase')}}</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.toLocaleUpperCase")}}</p> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("String.prototype.toLocaleLowerCase()")}}</li> + <li>{{jsxref("String.prototype.toLowerCase()")}}</li> + <li>{{jsxref("String.prototype.toUpperCase()")}}</li> +</ul> + +<div id="gtx-trans" style="position: absolute; left: 11px; top: 96px;"> +<div class="gtx-trans-icon"></div> +</div> 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 +--- +<div>{{JSRef}}</div> + +<p><code><strong>toLowerCase()</strong></code> 会将调用该方法的字符串值转为小写形式,并返回。</p> + +<h2 id="语法" style="margin-bottom: 20px; line-height: 30px;">语法</h2> + +<pre class="syntaxbox language-html notranslate" style="margin-bottom: 0px; padding: 1em; border-left-width: 6px; border-left-style: solid; font-family: Consolas, Monaco, 'Andale Mono', monospace; font-size: 14px; direction: ltr; white-space: normal; text-shadow: none; background-color: rgba(212, 221, 228, 0.498039);"><code class="language-html" style="font-family: Consolas, Monaco, 'Andale Mono', monospace; direction: ltr; color: inherit; text-shadow: none;">str.toLowerCase()</code> +</pre> + +<p id="sect1"></p> + +<h3 id="返回值">返回值</h3> + +<p>一个新的字符串,表示转换为小写的调用字符串。</p> + +<h2 id="描述" style="margin-bottom: 20px; line-height: 30px;">描述</h2> + +<p><code>toLowerCase</code> 会将调用该方法的字符串值转为小写形式,并返回。<code>toLowerCase</code> 不会影响字符串本身的值。</p> + +<h2 id="示例" style="margin-bottom: 20px; line-height: 30px;">示例</h2> + +<h3 id="例子:使用_toLowerCase" style="line-height: 24px;">例子:使用 <code>toLowerCase()</code></h3> + +<pre class="brush: js notranslate">console.log('中文简体 zh-CN || zh-Hans'.toLowerCase()); +// 中文简体 zh-cn || zh-hans + +console.log( "ALPHABET".toLowerCase() ); +// "alphabet"</pre> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 0px; background: 0px 0px;"></div> + +<p><font face="x-locale-heading-primary, zillaslab, Palatino, Palatino Linotype, x-locale-heading-secondary, serif"><span style="font-size: 37.33327865600586px;"><strong>说明</strong></span></font></p> + + + +<table> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.16', 'String.prototype.toLowerCase')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> <br> + </td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("String.prototype.toLocaleLowerCase()")}}</li> + <li>{{jsxref("String.prototype.toLocaleUpperCase()")}}</li> + <li>{{jsxref("String.prototype.toUpperCase()")}}</li> +</ul> 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 +--- +<div>{{JSRef}} {{non-standard_header}}</div> + +<p><strong><code>toSource()</code></strong> 方法返回一个代表对象的源代码。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code>String.toSource() +<var>str</var>.toSource() +</code></pre> + +<h2 id="描述">描述</h2> + +<p><code>toSource()</code> 方法返回以下值:</p> + +<p>对于内建对象 {{jsxref("String")}} , <code>toSource()返回以下值说明源码不可用:</code></p> + +<pre class="brush: js">function String() { + [native code] +} +</pre> + +<p>对于实例{{jsxref("String")}} 或者字符串, <code>toSource()</code> 返回一个字符串表示源码.</p> + +<p>这种方法通常在内部被JavaScript调用,而不是明确的代码。.</p> + +<h2 id="规范">规范</h2> + +<p>不属于任何标准. 在 JavaScript 1.3实现了.</p> + +<h2 id="浏览器适配">浏览器适配</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="参见">参见</h2> + +<ul> + <li>{{jsxref("Object.prototype.toSource()")}}</li> +</ul> 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 +--- +<div>{{JSRef("Global_Objects", "String")}}</div> + +<h2 id="Summary" name="Summary">概述</h2> + +<p><code><strong>toString()</strong></code> 方法返回指定对象的字符串形式。</p> + +<h2 id="Syntax" name="Syntax">语法</h2> + +<pre class="syntaxbox"><code><em>str</em>.toString()</code> +</pre> + +<h3 id="返回值">返回值</h3> + +<p>一个表示调用对象的字符串。</p> + +<h2 id="Description" name="Description">描述</h2> + +<p><code>String</code> 对象覆盖了{{jsxref("Global_Objects/Object", "Object")}} 对象的 <code>toString</code> 方法;并没有继承 {{jsxref("Object.toString()")}}。对于 <code>String</code> 对象,<code>toString</code> 方法返回该对象的字符串形式,和 {{jsxref("String.prototype.valueOf()")}} 方法返回值一样。</p> + +<h2 id="Examples" name="Examples">示例</h2> + +<h3 id="Example_Using_toString" name="Example:_Using_toString">例子:使用 <code>toString</code></h3> + +<p>下例输出一个字符串对象(String object)的字符串值:</p> + +<pre class="brush:js">var x = new String("Hello world"); + +alert(x.toString()) // 输出 "Hello world"</pre> + +<h2 id="规范">规范</h2> + +<table> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.2', 'String.prototype.toString')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.tostring', 'String.prototype.toString')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.tostring', 'String.prototype.toString')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also" name="See_also">相关链接</h2> + +<ul> + <li>{{jsxref("Object.prototype.toSource()")}}</li> + <li>{{jsxref("String.prototype.valueOf()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><strong><code>toUpperCase()</code></strong> 方法将调用该方法的字符串转为大写形式并返回(如果调用该方法的值不是字符串类型会被强制转换)。</p> + +<div>{{EmbedInteractiveExample("pages/js/string-touppercase.html","shorter")}}</div> + +<p class="hidden">这个交互式示例的源代码存储在GitHub存储库中。如果您想对交互式示例项目作出贡献,请克隆<a href="/zh-CN/docs/">https://github.com/mdn/interactive-examples</a>并向我们发送请求。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox notranslate"><var>str</var>.toUpperCase()</pre> + +<h3 id="返回值">返回值</h3> + +<p>一个新的字符串,表示转换为大写的调用字符串。</p> + +<h3 id="错误处理">错误处理</h3> + +<dl> + <dt>{{jsxref("TypeError(类型错误)")}}</dt> + <dd>在 {{jsxref("null")}} 或 {{jsxref("undefined")}}类型上调用,例如:<code>String.prototype.toUpperCase.call(undefined)</code>.</dd> +</dl> + +<h2 id="描述">描述</h2> + +<p><code>toUpperCase()</code> 返回转为大写形式的字符串。此方法不会影响原字符串本身的值,因为JavaScript中字符串的值是不可改变的。</p> + +<h2 id="示例">示例</h2> + +<h3 id="基本用法">基本用法</h3> + +<pre class="brush: js notranslate">console.log('alphabet'.toUpperCase()); // 'ALPHABET' +</pre> + +<h3 id="将非字符串类型的_this_(上下文)转为字符串">将非字符串类型的 <code>this</code> (上下文)转为字符串</h3> + +<p>此方法会将任何非字符串类型的值转为字符串, 当你将其上下文 <code>this</code> 值设置为非字符串类型</p> + +<pre class="brush: js notranslate">const a = String.prototype.toUpperCase.call({ + toString: function toString() { + return 'abcdef'; + } +}); + +const b = String.prototype.toUpperCase.call(true); + +// 输出 'ABCDEF TRUE'。 +console.log(a, b); +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.touppercase', 'String.prototype.toUpperCase')}}</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div class="hidden">此页中的兼容性表是从结构化数据生成的。如果你想对数据有所贡献,请查看<a href="/zh-CN/docs/">https://github.com/mdn/browser-compat-data</a>并向我们发送请求。</div> + +<p>{{Compat("javascript.builtins.String.toUpperCase")}}</p> + +<h2 id="参见">参见</h2> + +<ul> + <li>{{jsxref("String.prototype.toLocaleLowerCase()")}}</li> + <li>{{jsxref("String.prototype.toLocaleUpperCase()")}}</li> + <li>{{jsxref("String.prototype.toLowerCase()")}}</li> +</ul> 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 +--- +<div> +<div> +<div>{{JSRef}}</div> +</div> +</div> + +<p><strong><code>trim()</code> </strong>方法会从一个字符串的两端删除空白字符。在这个上下文中的空白字符是所有的空白字符 (space, tab, no-break space 等) 以及所有行终止符字符(如 LF,CR等)。</p> + +<p>{{EmbedInteractiveExample("pages/js/string-trim.html")}}</p> + + + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox notranslate"><code><var>str</var>.trim()</code></pre> + +<h3 id="返回值">返回值</h3> + +<p>一个代表调用字符串两端去掉空白的新字符串。</p> + +<h2 id="描述">描述</h2> + +<p><code>trim()</code> 方法返回一个从两头去掉空白字符的字符串,并不影响原字符串本身。</p> + +<h2 id="例子">例子</h2> + +<h3 id="使用_trim">使用 <code>trim()</code></h3> + +<p>下面的例子中将显示小写的字符串 'foo':</p> + +<pre class="brush: js notranslate">var orig = ' foo '; +console.log(orig.trim()); // 'foo' + +// 另一个 .trim() 例子,只从一边删除 + +var orig = 'foo '; +console.log(orig.trim()); // 'foo' +</pre> + +<h2 id="兼容旧环境">兼容旧环境</h2> + +<p>如果 <code>trim()</code> 不存在,可以在所有代码前执行下面代码</p> + +<pre class="brush: js notranslate">if (!String.prototype.trim) { + String.prototype.trim = function () { + return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); + }; +} +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.20', 'String.prototype.trim')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.8.1.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.trim', 'String.prototype.trim')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.trim', 'String.prototype.trim')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.trim")}}</p> + +<h2 id="参见">参见</h2> + +<ul> + <li>{{jsxref("String.prototype.trimStart()")}}</li> + <li>{{jsxref("String.prototype.trimEnd()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<div><strong><code>trimStart()</code> </strong>方法从字符串的开头删除空格。<code>trimLeft()</code> 是此方法的别名。</div> + +<div>{{EmbedInteractiveExample("pages/js/string-trimstart.html")}}</div> + + + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><var>str</var>.trimStart(); +<var>str</var>.trimLeft();</pre> + +<h3 id="返回值">返回值</h3> + +<p>一个新字符串,表示从其开头(左端)除去空格的调用字符串。</p> + +<h2 id="描述">描述</h2> + +<p><code>trimStart()</code> / <code>trimLeft()</code> 方法移除原字符串左端的连续空白符并返回一个新字符串,并不会直接修改原字符串本身。</p> + +<h3 id="别名">别名</h3> + +<p>为了与 {{jsxref("String.prototype.padStart")}} 等函数保持一致,标准方法名称为<code>trimStart</code>。 但是,出于 Web 兼容性原因,<code>trimLeft</code> 仍然是 <code>trimStart</code> 的别名。在某些引擎中,这意味着:</p> + +<pre class="brush: js">String.prototype.trimLeft.name === "trimStart";</pre> + +<h2 id="示例">示例</h2> + +<h3 id="使用_trimStart">使用 <code>trimStart()</code></h3> + +<p>下面的例子输出了小写的字符串 <code>"foo "</code>:</p> + +<pre class="brush:js;highlight:[5]">var str = " foo "; + +console.log(str.length); // 8 + +str = str.trimStart() // 等同于 str = str.trimLeft(); +console.log(str.length); // 5 +console.log(str); // "foo " +</pre> + +<h2 id="规范">规范</h2> + +<table> + <thead> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + </thead> + <tbody> + <tr> + <td><code><a href="https://github.com/tc39/proposal-string-left-right-trim/#stringprototypetrimstart--stringprototypetrimend">String.prototype.{trimStart,trimEnd}</a></code>proposal</td> + <td>Stage 4</td> + <td>Expected to be part of ES2019</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.trimStart")}}</p> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">// 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); +*/</pre> + +<h2 id="参见">参见</h2> + +<ul> + <li>{{jsxref("String.prototype.trim()")}}</li> + <li>{{jsxref("String.prototype.trimEnd()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><code><strong>trimEnd()</strong> </code>方法从一个字符串的末端移除空白字符。trimRight() 是这个方法的别名。</p> + +<p>{{EmbedInteractiveExample("pages/js/string-trimend.html")}}</p> + +<p>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 <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> + +<h2 id="Syntax" name="Syntax">语法</h2> + +<pre class="syntaxbox"><code><var>str</var>.trimEnd(); +<var>str</var>.trimRight();</code></pre> + +<h3 id="返回值">返回值</h3> + +<p>一个新字符串,表示从调用字串的末(右)端除去空白。</p> + +<h2 id="Description" name="Description">描述</h2> + +<p><code>trimEnd()</code> / <code>trimRight()</code>方法移除原字符串右端的连续空白符并返回,<code>trimEnd()</code> / <code>trimRight()</code>方法并不会直接修改原字符串本身。</p> + +<h3 id="别名">别名</h3> + +<p>为了与 {{jsxref("String.prototype.padEnd")}} 等函数保持一致,标准方法名称为<code>trimEnd</code>。 但是,出于Web兼容性原因,<code>trimRight</code>仍然是<code>trimEnd</code>的别名。 在某些引擎中,这意味着:</p> + +<pre class="brush: js"><code>String.prototype.trimRight.name === "trimEnd";</code> +</pre> + +<h2 id="Examples" name="Examples">示例</h2> + +<h3 id="使用trimEnd">使用<code>trimEnd()</code></h3> + +<p>下面的例子输出了小写的字符串" foo":</p> + +<pre class="brush:js;highlight:[5]">var str = " foo "; + +alert(str.length); // 8 + +str = str.trimRight(); // 或写成str = str.trimEnd(); +console.log(str.length); // 6 +console.log(str); // ' foo' +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td><code><a href="https://github.com/tc39/proposal-string-left-right-trim/#stringprototypetrimstart--stringprototypetrimend">String.prototype.{trimStart,trimEnd}</a></code>proposal</td> + <td>Stage 4</td> + <td>Expected to be part of ES2019</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.trimEnd")}}</p> + +<h2 id="See_also" name="See_also">相关链接</h2> + +<ul> + <li>{{jsxref("String.prototype.trim()")}}</li> + <li>{{jsxref("String.prototype.trimStart()")}}</li> +</ul> 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 +--- +<div>{{JSRef}}</div> + +<p><strong><code>valueOf()</code></strong> 方法返回 {{jsxref("String")}} 对象的原始值</p> + +<div>{{EmbedInteractiveExample("pages/js/string-valueof.html")}}</div> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox notranslate"><code><var>str</var>.valueOf()</code></pre> + +<h3 id="返回结果">返回结果</h3> + +<p>A string representing the primitive value of a given {{jsxref("String")}} object.</p> + +<h2 id="描述">描述</h2> + +<p>The <code>valueOf()</code> 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()")}}.</p> + +<p>此方法通常由JavaScript在内部调用,而不是在代码中显式调用。</p> + +<h2 id="示例">示例</h2> + +<h3 id="使用_valueOf">使用 <code>valueOf()</code></h3> + +<pre class="brush: js notranslate">var x = new String('Hello world'); +console.log(x.valueOf()); // Displays 'Hello world' +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.valueof', 'String.prototype.valueOf')}}</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p class="hidden">此页中的兼容性表是从结构化数据生成的。如果你想对数据有所贡献,请查看<a href="/zh-CN/docs/">https://github.com/mdn/browser-compat-data</a>并向我们发送请求。</p> + +<p>{{Compat("javascript.builtins.String.valueOf")}}</p> + +<h2 id="参见">参见</h2> + +<ul> + <li>{{jsxref("String.prototype.toString()")}}</li> + <li>{{jsxref("Object.prototype.valueOf()")}}</li> +</ul> |