aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/web/javascript/reference/global_objects/string/index.html
blob: 8ab9244b71e5f2e2c4462324ef17d70994d45c16 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
---
title: 字串
slug: Web/JavaScript/Reference/Global_Objects/String
tags:
  - ECMAScript 2015
  - JavaScript
  - Reference
  - String
translation_of: Web/JavaScript/Reference/Global_Objects/String
---
<p>{{JSRef("Global_Objects", "String")}}</p>

<p><strong><code>String</code></strong> 全域物件為字串的構造函數,或是一個字符序列。</p>

<h2 id="Syntax" name="Syntax">語法</h2>

<p>字串文字採用下列形式:</p>

<pre>'string text' "string text" "中文 español deutsch English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ் עברית"</pre>

<p>字串也可以被全域的 <code>String</code> 物件建立:</p>

<pre>String(thing)</pre>

<h3 id="Parameters" name="Parameters">參數</h3>

<dl>
 <dt><code>thing</code></dt>
 <dd>任何要轉換成字串的物件。</dd>
</dl>

<h3 id="樣板字面值">樣板字面值</h3>

<p>自 ECMAScript 2015,字串文字也可以是<a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Template_literals">樣板字面值(Template literals)</a></p>

<pre>`hello world` `hello! world!` `hello ${who}` escape `&lt;a&gt;${who}&lt;/a&gt;`</pre>

<h3 id="跳脫符號">跳脫符號</h3>

<p>除了常規的、可印出來的字元,特殊字元也可以被跳脫符號來表示編碼。</p>

<table>
 <thead>
  <tr>
   <th scope="col">代碼</th>
   <th scope="col">輸出</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>雙引號</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>回車</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 代碼 {{experimental_inline}}</td>
  </tr>
  <tr>
   <td><code>\xXX</code></td>
   <td>Latin-1 字元</td>
  </tr>
 </tbody>
</table>

<dl>
</dl>

<div class="note">
<p>和其他語言不同,JavaScript 將單引號字串和雙引號字串是做相同;因此,上述的序列可以在單引號或雙引號中作用。</p>
</div>

<dl>
</dl>

<h3 id="長字面值字串">長字面值字串</h3>

<p>有些時候,你的程式碼會包含非常長的字串。 為了不讓長字串無止盡地往下長,抑或是在你心血來潮的時候,你可能希望將這樣長的字串能夠斷成多行卻不影響到實際的內容。</p>

<p>你可以用 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition_()">+</a> 運算子附加多個字串在一起,像是這樣:</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>

<h2 id="Description" name="Description">說明</h2>

<p>字串對於能保留以文字形式表達的資料這件事來說,是有用的。在字串上,一些最常被使用的運算即確認字串長度 {{jsxref("String.length", "length")}} ,用 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/String_Operators">+ 或 += 字串運算元</a> 建造或者串接字串,用 {{jsxref("String.indexOf", "indexOf")}} 方法檢查?子字串是否存在或子字串的位置,或者是用 {{jsxref("String.substring", "substring")}} 方法將子字串抽取出來。</p>

<h3 id="Character_access" name="Character_access">存取字元</h3>

<p>有兩個方法可以存取字串中個別的字元。第一個是用 {{jsxref("String.charAt", "charAt")}} 方法:</p>

<pre class="brush: js">return 'cat'.charAt(1); // 回傳 "a"
</pre>

<p>另一個(在ECMAScript 5中被提到)方法是將字串當作一個類似陣列的物件,直接存取字串中對應的數值索引。</p>

<pre class="brush: js">return 'cat'[1]; // 回傳 "a"
</pre>

<p>對於存取字元使用的括號表達式,沒辦法去刪除或指派一個值給這些屬性。 這些屬性既非可寫的,也非可設定的。(參見 {{jsxref("Object.defineProperty")}})</p>

<h3 id="Comparing_strings" name="Comparing_strings">比較字串</h3>

<p>C 語言的開發者有 <code>strcmp()</code> 函式可以用來比較字串。 在 JavaScript 中,你只能用<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">小於和大於運算子</a></p>

<pre class="brush: js">var a = "a";
var b = "b";
if (a &lt; b) // true
  print(a + " 小於 " + b);
else if (a &gt; b)
  print(a + " 大於 " + b);
else
  print(a + " 和 " + b + " 相等");
</pre>

<p>這樣類似的結果,也能使用繼承 <code>String</code> 實體的 {{jsxref("String.localeCompare", "localeCompare")}} 方法來實現。</p>

<h3 id="分辨_string_原始型別和_String_物件">分辨 string 原始型別和 <code>String</code> 物件</h3>

<p>請注意,JavaScript 會區別 <code>String</code> 物件和原始字串({{jsxref("Global_Objects/Boolean", "Boolean")}} 和 {{jsxref("Global_Objects/Number", "Numbers")}} 也是如此)。</p>

<p>String literals (denoted by double or single quotes) and strings returned from <code>String</code> calls in a non-constructor context (i.e., without using the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/new"><code>new</code> keyword</a>) are primitive strings. JavaScript automatically converts primitives to <code>String</code> objects, so that it's possible to use <code>String</code> object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.</p>

<pre class="brush: js">var s_prim = "foo";
var s_obj = new String(s_prim);

console.log(typeof s_prim); // 印出 "string"
console.log(typeof s_obj);  // 印出 "object"
</pre>

<p>字串原始型別和 <code>String</code> 物件也會在使用 {{jsxref("Global_Objects/eval", "eval")}} 時給出不同的結果。 原始型別傳進 <code>eval</code> 會被視為原始代碼;<code>String</code> 物件則會回傳,且被視作是其他物件。舉個例子:</p>

<pre class="brush: js">s1 = "2 + 2";               // 建立一個字串原始型別
s2 = new String("2 + 2");   // 建立一個字串物件
console.log(eval(s1));      // 回傳數字 4
console.log(eval(s2));      // 回傳字串 "2 + 2"
</pre>

<p>因為一些原因,程式碼也許在遇到 <code>String</code> 物件時,但需要的卻是字串原始型別;儘管如此,通常作者們不需要擔心它的差異。</p>

<p>一個 <code>String</code> 物件總能夠使用 {{jsxref("String.valueOf", "valueOf")}} 方法被轉換成自身的原始副本。</p>

<pre class="brush: js">console.log(eval(s2.valueOf())); // 回傳數字 4
</pre>

<div class="note"><strong>注意:</strong> 對於在 JavaScript 中其他可用的字串方法,請參閱這篇文章<a href="/en-US/docs/Web/JavaScript/Typed_arrays/StringView" title="/en-US/docs/Web/JavaScript/Typed_arrays/StringView"><code>StringView</code> – a C-like representation of strings based on typed arrays</a></div>

<h2 id="Properties" name="Properties">屬性</h2>

<dl>
 <dt>{{jsxref("String.prototype")}}</dt>
 <dd>能讓字串物件增加屬性。</dd>
</dl>

<div>{{jsOverrides("Function", "Properties", "prototype")}}</div>

<h2 id="Methods" name="Methods">方法</h2>

<dl>
 <dt>{{jsxref("String.fromCharCode()")}}</dt>
 <dd>利用 Unicode 值的序列建立並回傳一個字串。</dd>
 <dt>{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}</dt>
 <dd>利用編碼位置的序列建立並回傳一個字串。</dd>
</dl>

<div>{{jsOverrides("Function", "Methods", "fromCharCode", "fromCodePoint")}}</div>

<h2 id="String_通用方法"><code>String</code> 通用方法</h2>

<div class="warning">
<p>字串通用方法是非標準化的、被棄用的,也有近期將被刪除的。</p>
</div>

<p>The <code>String </code>instance methods are also available in Firefox as of JavaScript 1.6 (though not part of the ECMAScript standard) on the String object for applying String methods to any object:</p>

<pre class="brush: js">var num = 15;
alert(String.replace(num, /5/, '2'));
</pre>

<p class="brush: js"><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Array_generic_methods">Generics</a> are also available on {{jsxref("Global_Objects/Array", "Array")}} methods.</p>

<p class="brush: js">The following is a shim to provide support to non-supporting browsers:</p>

<pre class="brush: js">/*globals define*/
// Assumes all supplied String instance methods already present
// (one may use shims for these if not available)
(function () {
    'use strict';

    var i,
        // We could also build the array of methods with the following, but the
        //   getOwnPropertyNames() method is non-shimable:
        // Object.getOwnPropertyNames(String).filter(function (methodName)
        //  {return typeof String[methodName] === 'function'});
        methods = [
            'quote', 'substring', 'toLowerCase', 'toUpperCase', 'charAt',
            'charCodeAt', 'indexOf', 'lastIndexOf', 'startsWith', 'endsWith',
            'trim', 'trimLeft', 'trimRight', 'toLocaleLowerCase',
            'toLocaleUpperCase', 'localeCompare', 'match', 'search',
            'replace', 'split', 'substr', 'concat', 'slice'
        ],
        methodCount = methods.length,
        assignStringGeneric = function (methodName) {
            var method = String.prototype[methodName];
            String[methodName] = function (arg1) {
                return method.apply(arg1, Array.prototype.slice.call(arguments, 1));
            };
        };

    for (i = 0; i &lt; methodCount; i++) {
        assignStringGeneric(methods[i]);
    }
}());</pre>

<h2 id="String_instances" name="String_instances"><code>String</code> instances</h2>

<h3 id="Properties_2">Properties</h3>

<p>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}</p>

<p>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods')}}</p>

<h2 id="Examples">Examples</h2>

<h3 id="String_conversion">String conversion</h3>

<p>It's possible to use <code>String</code> as a "safer" {{jsxref("String.toString", "toString")}} alternative, as although it still normally calls the underlying <code>toString</code>, it also works for <code>null</code> and <code>undefined</code>. For example:</p>

<pre class="brush: js">var outputStrings = [];
for (let i = 0, n = inputValues.length; i &lt; 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>{{SpecName('ES1')}}</td>
   <td>{{Spec2('ES1')}}</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('ES2015', '#sec-string-objects', 'String')}}</td>
   <td>{{Spec2('ES2015')}}</td>
   <td> </td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-string-objects', 'String')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td> </td>
  </tr>
 </tbody>
</table>

<h2 id="瀏覽器相容性">瀏覽器相容性</h2>

<p>{{Compat("javascript.builtins.String.String")}}</p>

<h2 id="參見">參見</h2>

<ul>
 <li>{{domxref("DOMString")}}</li>
 <li><a href="/en-US/Add-ons/Code_snippets/StringView"><code>StringView</code> — a C-like representation of strings based on typed arrays</a></li>
 <li><a href="/en-US/docs/Web/API/DOMString/Binary">Binary strings</a></li>
</ul>