uTools-Manuals/docs/javascript/Guide/Text_formatting.html
2019-04-21 11:50:48 +08:00

192 lines
18 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<article id="wikiArticle">
<div> <div class="prevnext" style="text-align: right;">
<p><a href="Guide/Numbers_and_dates" style="float: left;">« 上一页</a><a href="Guide/Regular_Expressions">下一页 »</a></p>
</div></div>
<p class="summary">本章介绍在Javascript中如何使用字符串与文本内容。</p>
<h2 id="字符串">字符串</h2>
<p>JavaScript中的 <a class="glossaryLink" href="/en-US/docs/Glossary/String" title="String: In any computer programming language, a string is a sequence of characters used to represent text.">String</a> 类型用于表示文本型的数据. 它是由无符号整数值16bit作为元素而组成的集合. 字符串中的每个元素在字符串中占据一个位置. 第一个元素的index值是0, 下一个元素的index值是1, 以此类推. 字符串的长度就是字符串中所含的元素个数.你可以通过String字面值或者String对象两种方式创建一个字符串。</p>
<h3 id="String字面量">String字面量</h3>
<p>可以使用单引号或双引号创建简单的字符串:</p>
<pre><code class="language-javascript">'foo'
"bar"</code></pre>
<p>可以使用转义序列来创建更复杂的字符串:</p>
<h4 id="16进制转义序列">16进制转义序列</h4>
<p>\x之后的数值将被认为是一个16进制数.</p>
<pre><code class="language-javascript">'\xA9' // "©"
</code></pre>
<h4 id="Unicode转义序列">Unicode转义序列</h4>
<p>Unicode转义序列在\u之后需要至少4个字符.</p>
<pre><code class="language-javascript">'\u00A9' // "©"</code></pre>
<h4 id="Unicode字元逸出">Unicode字元逸出</h4>
<p>这是ECMAScript 6中的新特性。有了Unicode字元逸出任何字符都可以用16进制数转义, 这使得通过Unicode转义表示大于<code>0x10FFFF</code>的字符成为可能。使用简单的Unicode转义时通常需要分别写字符相应的两个部分译注大于<span style="font-family: courier,andale mono,monospace;">0x10FFFF的字符需要拆分为相应的两个小于0x10FFFF的部分</span>)来达到同样的效果。</p>
<p>请参阅 <a href="Reference/Global_Objects/String/fromCodePoint" title="String.fromCodePoint() 静态方法返回使用指定的代码点序列创建的字符串。"><code>String.fromCodePoint()</code></a><a href="Reference/Global_Objects/String/codePointAt" title="codePointAt() 方法返回 一个 Unicode 编码点值的非负整数。"><code>String.prototype.codePointAt()</code></a></p>
<pre><code class="language-javascript">'\u{2F804}'
// the same with simple Unicode escapes
'\uD87E\uDC04'</code></pre>
<h3 id="字符串对象">字符串对象</h3>
<p><a href="Reference/String" title="此页面仍未被本地化, 期待您的翻译!"><code>String</code></a> 对象是对原始string类型的封装 .</p>
<pre><code class="language-javascript">var s = new String("foo"); // Creates a String object
console.log(s); // Displays: { '0': 'f', '1': 'o', '2': 'o'}
typeof s; // Returns 'object'
</code></pre>
<p>你可以在String字面值上使用String对象的任何方法—JavaScript自动把String字面值转换为一个临时的String对象, 然后调用其相应方法,最后丢弃此临时对象.在String字面值上也可以使用String.length属性.</p>
<p>除非必要, 应该尽量使用String字面值, 因为String对象的某些行为可能并不与直觉一致. 举例:</p>
<pre><code class="language-javascript">var s1 = "2 + 2"; // Creates a string literal value
var s2 = new String("2 + 2"); // Creates a String object
eval(s1); // Returns the number 4
eval(s2); // Returns the string "2 + 2"</code></pre>
<p><code>String对象有一个属性</code>, <code>length</code>, 标识了字符串中的字符个数.举例, 下面的代码把13赋值给了<code>x</code>, 因为"Hello, World!"包含了13个字符译注注意W之前有个空格:</p>
<pre><code class="language-javascript">var mystring = "Hello, World!";
var x = mystring.length;
</code></pre>
<p><code>String</code>对象有许多方法: 举例来说有些方法返回字符串本身的变体, 如 <code>substring</code><code>toUpperCase</code>.</p>
<p>下表总结了 <a href="Reference/String" title="此页面仍未被本地化, 期待您的翻译!"><code>String</code></a> 对象的方法.</p>
<table class="standard-table">
<caption>
<h4 id="String对象方法">String对象方法</h4>
</caption>
<thead>
<tr>
<th scope="col">方法</th>
<th scope="col">描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="Reference/Global_Objects/String/charAt" title="charAt() 方法从一个字符串中返回指定的字符。"><code>charAt</code></a>, <a href="Reference/Global_Objects/String/charCodeAt" title="charCodeAt() 方法返回0到65535之间的整数表示给定索引处的UTF-16代码单元 (在 Unicode 编码单元表示一个单一的 UTF-16 编码单元的情况下UTF-16 编码单元匹配 Unicode 编码单元。但在——例如 Unicode 编码单元 &gt; 0x10000 的这种——不能被一个 UTF-16 编码单元单独表示的情况下只能匹配 Unicode 代理对的第一个编码单元) 。如果你想要整个代码点的值,使用 codePointAt()。"><code>charCodeAt</code></a>, <a href="Reference/Global_Objects/String/codePointAt" title="codePointAt() 方法返回 一个 Unicode 编码点值的非负整数。"><code>codePointAt</code></a></td>
<td>返回字符串指定位置的字符或者字符编码。</td>
</tr>
<tr>
<td><a href="Reference/Global_Objects/String/indexOf" title="indexOf() 方法返回调用  String 对象中第一次出现的指定值的索引开始在 fromIndex进行搜索。"><code>indexOf</code></a>, <a href="Reference/Global_Objects/String/lastIndexOf" title="lastIndexOf() 方法返回指定值在调用该方法的字符串中最后出现的位置,如果没找到则返回 -1。从该字符串的后面向前查找从 fromIndex 处开始。"><code>lastIndexOf</code></a></td>
<td>分别返回字符串中指定子串的位置或最后位置。</td>
</tr>
<tr>
<td><a href="Reference/Global_Objects/String/startsWith" title="startsWith()方法用来判断当前字符串是否是以另外一个给定的子字符串“开头”的,根据判断结果返回 true 或 false。"><code>startsWith</code></a>, <a href="Reference/Global_Objects/String/endsWith" title="endsWith()方法用来判断当前字符串是否是以另外一个给定的子字符串“结尾”的,根据判断结果返回 true 或 false。"><code>endsWith</code></a>, <a href="Reference/Global_Objects/String/includes" title="includes() 方法用于判断一个字符串是否包含在另一个字符串中,根据情况返回 true 或 false。"><code>includes</code></a></td>
<td>返回字符串是否以指定字符串开始、结束或包含指定字符串。</td>
</tr>
<tr>
<td><a href="Reference/Global_Objects/String/concat" title="concat() 方法将一个或多个字符串与原字符串连接合并,形成一个新的字符串并返回。"><code>concat</code></a></td>
<td>连接两个字符串并返回新的字符串。</td>
</tr>
<tr>
<td><a href="Reference/Global_Objects/String/fromCharCode" title="静态 String.fromCharCode() 方法返回由指定的UTF-16代码单元序列创建的字符串。"><code>fromCharCode</code></a>, <a href="Reference/Global_Objects/String/fromCodePoint" title="String.fromCodePoint() 静态方法返回使用指定的代码点序列创建的字符串。"><code>fromCodePoint</code></a></td>
<td>从指定的Unicode值序列构造一个字符串。这是一个String类方法不是实例方法。</td>
</tr>
<tr>
<td><a href="Reference/Global_Objects/String/split" title="split() 方法使用指定的分隔符字符串将一个String对象分割成字符串数组以将字符串分隔为子字符串以确定每个拆分的位置。"><code>split</code></a></td>
<td>通过将字符串分离成一个个子串来把一个String对象分裂到一个字符串数组中。</td>
</tr>
<tr>
<td><a href="Reference/Global_Objects/String/slice" title="slice() 方法提取一个字符串的一部分,并返回一新的字符串。"><code>slice</code></a></td>
<td>从一个字符串提取片段并作为新字符串返回。</td>
</tr>
<tr>
<td><a href="Reference/Global_Objects/String/substring" title="substring() 方法返回一个字符串在开始索引到结束索引之间的一个子集, 或从开始索引直到字符串的末尾的一个子集。"><code>substring</code></a>, <a href="Reference/Global_Objects/String/substr" title="substr() 方法返回一个字符串中从指定位置开始到指定字符数的字符。"><code>substr</code></a></td>
<td>分别通过指定起始和结束位置,起始位置和长度来返回字符串的指定子集。</td>
</tr>
<tr>
<td><a href="Reference/Global_Objects/String/match" title="match() 方法检索返回一个字符串匹配正则表达式的的结果。"><code>match</code></a>, <a href="Reference/Global_Objects/String/replace" title="replace() 方法返回一个由替换值replacement替换一些或所有匹配的模式pattern后的新字符串。模式可以是一个字符串或者一个正则表达式替换值可以是一个字符串或者一个每次匹配都要调用的函数。"><code>replace</code></a>, <a href="Reference/Global_Objects/String/search" title="search() 方法执行正则表达式和 String对象之间的一个搜索匹配。"><code>search</code></a></td>
<td>通过正则表达式来工作.</td>
</tr>
<tr>
<td><a href="Reference/Global_Objects/String/toLowerCase" title="toLowerCase() 会将调用该方法的字符串值转为小写形式,并返回。"><code>toLowerCase</code></a>, <a href="Reference/Global_Objects/String/toUpperCase" title="toUpperCase() 将调用该方法的字符串值转换为大写形式,并返回。"><code>toUpperCase</code></a></td>
<td>
<p>分别返回字符串的小写表示和大写表示。</p>
</td>
</tr>
<tr>
<td><a href="Reference/Global_Objects/String/normalize" title="normalize() 方法会按照指定的一种 Unicode 正规形式将当前字符串正规化."><code>normalize</code></a></td>
<td>按照指定的一种 Unicode 正规形式将当前字符串正规化。</td>
</tr>
<tr>
<td><a href="Reference/Global_Objects/String/repeat" title="repeat() 构造并返回一个新字符串,该字符串包含被连接在一起的指定数量的字符串的副本。"><code>repeat</code></a></td>
<td>将字符串内容重复指定次数后返回。</td>
</tr>
<tr>
<td><a href="Reference/Global_Objects/String/trim" title="trim() 方法会从一个字符串的两端删除空白字符。在这个上下文中的空白字符是所有的空白字符 (space, tab, no-break space 等) 以及所有行终止符字符(如 LFCR。"><code>trim</code></a></td>
<td>去掉字符串开头和结尾的空白字符。</td>
</tr>
</tbody>
</table>
<h3 id="多行模板字符串">多行模板字符串</h3>
<p>模板字符串是一种允许内嵌表达式的String字面值. 可以用它实现多行字符串或者字符串内插等特性.</p>
<p>模板字符串使用反勾号 (` `) (<a class="external external-icon" href="https://en.wikipedia.org/wiki/Grave_accent" rel="noopener">grave accent</a>) 包裹内容而不是单引号或双引号. 模板字符串可以包含占位符. 占位符用美元符号和花括号标识 (<code>${expression}</code>).</p>
<h4 id="多行">多行</h4>
<p>源代码中插入的任何新行开始字符都作为模板字符串的内容. 使用一般的字符串时, 为了创建多行的字符串不得不用如下语法:</p>
<pre><code class="language-javascript">console.log("string text line 1\n\
string text line 2");
// "string text line 1
// string text line 2"</code></pre>
<p>为了实现同样效果的多行字符串, 现在可以写成如下形式:</p>
<pre><code class="language-javascript">console.log(`string text line 1
string text line 2`);
// "string text line 1
// string text line 2"</code></pre>
<h4 id="嵌入表达式">嵌入表达式</h4>
<p>为了在一般的字符串中嵌入表达式, 需要使用如下语法:</p>
<pre><code class="language-javascript">var a = 5;
var b = 10;
console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + ".");
// "Fifteen is 15 and
// not 20."</code></pre>
<p>现在, 使用模板字符串, 可以使用语法糖让类似功能的实现代码更具可读性:</p>
<pre><code class="language-javascript">var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}.`);
// "Fifteen is 15 and
// not 20."</code></pre>
<p>更多信息, 请阅读 <a href="/en-US/docs/Web/JavaScript/Reference">JavaScript reference</a> 中的 <a href="/en-US/docs/Web/JavaScript/Reference/template_strings">Template strings</a></p>
<h2 id="国际化">国际化</h2>
<p><a href="Reference/Global_Objects/Intl" title="Intl 对象是 ECMAScript 国际化 API 的一个命名空间它提供了精确的字符串对比、数字格式化和日期时间格式化。CollatorNumberFormat 和 DateTimeFormat 对象的构造函数是 Intl 对象的属性。本页文档内容包括了这些属性,以及国际化使用的构造器和其他语言的方法等常见的功能。"><code>Intl</code></a> 对象是ECMAScript国际化API的命名空间, 它提供了语言敏感的字符串比较,数字格式化和日期时间格式化功能.  <a href="Reference/Global_Objects/Collator" title="Intl.Collator 是用于语言敏感字符串比较的 collators构造函数。"><code>Collator</code></a>, <a href="Reference/Global_Objects/NumberFormat" title="Intl.NumberFormat是对语言敏感的格式化数字类的构造器类"><code>NumberFormat</code></a>, 和 <a href="Reference/Global_Objects/DateTimeFormat" title="交互示例的源代码存储在 GitHub 资源库。如果你愿意分布交互示例请复制https://github.com/mdn/interactive-examples并向我们发送一个pull请求。"><code>DateTimeFormat</code></a> 对象的构造函数是<code>Intl</code>对象的属性.</p>
<h3 id="日期和时间格式化">日期和时间格式化</h3>
<p><a href="Reference/Global_Objects/DateTimeFormat" title="交互示例的源代码存储在 GitHub 资源库。如果你愿意分布交互示例请复制https://github.com/mdn/interactive-examples并向我们发送一个pull请求。"><code>DateTimeFormat</code></a> 对象在日期和时间的格式化方面很有用. 下面的代码把一个日期格式化为美式英语格式. (不同时区结果不同.)</p>
<pre><code class="language-javascript">var msPerDay = 24 * 60 * 60 * 1000;
// July 17, 2014 00:00:00 UTC.
var july172014 = new Date(msPerDay * (44 * 365 + 11 + 197));//2014-1970=44年
//这样创建日期真是醉人。。。还要自己计算天数。。。11是闰年中多出的天数。。。
//197是6×30+16(7月的16天)+3(3个大月)-2(2月少2天)
var options = { year: "2-digit", month: "2-digit", day: "2-digit",
    hour: "2-digit", minute: "2-digit", timeZoneName: "short" };
var americanDateTime = new Intl.DateTimeFormat("en-US", options).format;
 
console.log(americanDateTime(july172014)); // 07/16/14, 5:00 PM PDT
</code></pre>
<h3 id="数字格式化">数字格式化</h3>
<p><a href="Reference/Global_Objects/NumberFormat" title="Intl.NumberFormat是对语言敏感的格式化数字类的构造器类"><code>NumberFormat</code></a> 对象在数字的格式化方面很有用, 比如货币数量值.</p>
<pre><code class="language-javascript">var gasPrice = new Intl.NumberFormat("en-US",
                        { style: "currency", currency: "USD",
                          minimumFractionDigits: 3 });
 
console.log(gasPrice.format(5.259)); // $5.259
var hanDecimalRMBInChina = new Intl.NumberFormat("zh-CN-u-nu-hanidec",
                        { style: "currency", currency: "CNY" });
 
console.log(hanDecimalRMBInChina.format(1314.25)); // ¥ 一,三一四.二五
</code></pre>
<h3 id="定序">定序</h3>
<p><a href="Reference/Global_Objects/Collator" title="Intl.Collator 是用于语言敏感字符串比较的 collators构造函数。"><code>Collator</code></a> 对象在字符串比较和排序方面很有用.</p>
<p>举例, 德语中<em>有两种不同的排序方式 电话本phonebook</em> 和 字典(<em>dictionary</em>. 电话本排序强调发音, 比如在排序前 “ä”, “ö”等被扩展为 “ae”, “oe”等发音.</p>
<pre><code class="language-javascript">var names = ["Hochberg", "Hönigswald", "Holzman"];
 
var germanPhonebook = new Intl.Collator("de-DE-u-co-phonebk");
 
// as if sorting ["Hochberg", "Hoenigswald", "Holzman"]:
console.log(names.sort(germanPhonebook.compare).join(", "));
// logs "Hochberg, Hönigswald, Holzman"
</code></pre>
<p>有些德语词包含变音, 所以在字典中忽略变音进行排序是合理的 (除非待排序的单词只有变音部分不同: <em>schon</em> 先于 <em>schön</em>).</p>
<pre><code class="language-javascript">var germanDictionary = new Intl.Collator("de-DE-u-co-dict");
 
// as if sorting ["Hochberg", "Honigswald", "Holzman"]:
console.log(names.sort(germanDictionary.compare).join(", "));
// logs "Hochberg, Holzman, Hönigswald"
</code></pre>
<p>关于<a href="Reference/Global_Objects/Intl" title="Intl 对象是 ECMAScript 国际化 API 的一个命名空间它提供了精确的字符串对比、数字格式化和日期时间格式化。CollatorNumberFormat 和 DateTimeFormat 对象的构造函数是 Intl 对象的属性。本页文档内容包括了这些属性,以及国际化使用的构造器和其他语言的方法等常见的功能。"><code>Intl</code></a> API的更多信息, 请参考 <a class="external" href="https://hacks.mozilla.org/2014/12/introducing-the-javascript-internationalization-api/" rel="noopener">Introducing the JavaScript Internationalization API</a></p>
<div><div class="prevnext" style="text-align: right;">
<p><a href="Guide/Numbers_and_dates" style="float: left;">« 上一页</a><a href="Guide/Regular_Expressions">下一页 »</a></p>
</div></div>
</article>