aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/learn/javascript/first_steps/strings/index.html
blob: 8e4a3b1f6aada39f714f6b2c089218141d90d960 (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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
---
title: 處理文字 - JavaScript中的字串
slug: Learn/JavaScript/First_steps/Strings
tags:
  - JavaScript
  - 初學者
  - 字串
  - 引號
  - 文章
  - 連接字串
translation_of: Learn/JavaScript/First_steps/Strings
---
<div>{{LearnSidebar}}</div>

<div>{{PreviousMenuNext("Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps")}}</div>

<p class="summary">接下來我們將把注意力轉向字串——這就是程式設計中調用的文字片段。在本文中,我們將介紹在學習JavaScript時您應該了解所有有關字串的常見事項,例如建立字串,跳脫字串中的引號以及將字串連接在一起。</p>

<table class="learn-box standard-table">
 <tbody>
  <tr>
   <th scope="row">先備知識:</th>
   <td>基本的電腦素養、對 HTML 與 CSS 有基本的認識、對 JavaScript 有認識。</td>
  </tr>
  <tr>
   <th scope="row">目標:</th>
   <td>熟悉 JavaScript 字串的基礎。</td>
  </tr>
 </tbody>
</table>

<h2 id="文字的力量">文字的力量</h2>

<p>文字對人類而言非常重要——它關乎我們如何交流、溝通。Web 以文字為基底的媒介,它的設計讓人類可以進行交流並分享資訊,因此掌握文字如何在 Web 上呈現是很有用的。{{glossary("HTML")}} 提供文字的結構以及定義;{{glossary("CSS")}} 讓我們更精確地設定樣式;而 JavaScript 則包含許多操作字串的特性,例如:製作客製化的歡迎訊息、正確地顯示所需的文字標籤、排列所需的詞語順序等。</p>

<p>到目前為止,所有我們課程上的編碼幾乎都包含一些字串的操作。</p>

<h2 id="字串_—_基礎">字串 — 基礎</h2>

<p>剛開始你會覺得字串與數字的處理方式很類似,但當你越深入就會了解到一些明顯的差異。讓我們從在 console 裡輸入一些基本的程式行來熟悉它吧!在下方,我們提供一個 Console (你也可以另開一個頁籤或視窗<a href="https://mdn.github.io/learning-area/javascript/introduction-to-js-1/variables/index.html">使用他</a> ,或者使用瀏覽器的<a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">開發者工具</a>)。</p>

<div class="hidden">
<h6 id="Hidden_code">Hidden code</h6>

<pre class="brush: html notranslate">&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;JavaScript console&lt;/title&gt;
    &lt;style&gt;
      * {
        box-sizing: border-box;
      }

      html {
        background-color: #0C323D;
        color: #809089;
        font-family: monospace;
      }

      body {
        max-width: 700px;
      }

      p {
        margin: 0;
        width: 1%;
        padding: 0 1%;
        font-size: 16px;
        line-height: 1.5;
        float: left;
      }

      .input p {
        margin-right: 1%;
      }

      .output p {
        width: 100%;
      }

      .input input {
        width: 96%;
        float: left;
        border: none;
        font-size: 16px;
        line-height: 1.5;
        font-family: monospace;
        padding: 0;
        background: #0C323D;
        color: #809089;
      }

      div {
        clear: both;
      }

    &lt;/style&gt;
  &lt;/head&gt;
  &lt;body&gt;


  &lt;/body&gt;

  &lt;script&gt;
    var geval = eval;
    function createInput() {
      var inputDiv = document.createElement('div');
      var inputPara = document.createElement('p');
      var inputForm = document.createElement('input');

      inputDiv.setAttribute('class','input');
      inputPara.textContent = '&gt;';
      inputDiv.appendChild(inputPara);
      inputDiv.appendChild(inputForm);
      document.body.appendChild(inputDiv);

      if(document.querySelectorAll('div').length &gt; 1) {
        inputForm.focus();
      }

      inputForm.addEventListener('change', executeCode);
    }

    function executeCode(e) {
      try {
        var result = geval(e.target.value);
      } catch(e) {
        var result = 'error — ' + e.message;
      }

      var outputDiv = document.createElement('div');
      var outputPara = document.createElement('p');

      outputDiv.setAttribute('class','output');
      outputPara.textContent = 'Result: ' + result;
      outputDiv.appendChild(outputPara);
      document.body.appendChild(outputDiv);

      e.target.disabled = true;
      e.target.parentNode.style.opacity = '0.5';

      createInput()
    }

    createInput();

  &lt;/script&gt;
&lt;/html&gt;</pre>
</div>

<p>{{ EmbedLiveSample('Hidden_code', '100%', 300, "", "", "hide-codepen-jsfiddle") }}</p>

<h3 id="建立字串">建立字串</h3>

<ol>
 <li>首先,先輸入下面幾行程式碼:
  <pre class="brush: js notranslate">let string = 'The revolution will not be televised.';
string;</pre>
  就像我們對數字的操作,我們聲明一個變數,並用一個值(字串)來初始化它,而後傳回這個值。唯一的差異在於,你需要用引號包住你的值。</li>
 <li>如果你沒有使用引號包住值,或缺少單一邊的引號,都會導致錯誤產生。試著輸入下面幾行程式碼:
  <pre class="brush: js example-bad notranslate">let badString = This is a test;
let badString = 'This is a test;
let badString = This is a test';</pre>
  上述的程式無法運作,因為未使用引號包圍的文字都將被視為變數名稱、屬性名稱和保留字等。如果瀏覽器無法辨識它,便會產生錯誤(例如:「missing ; before statement」)。如果瀏覽器可以識別字段從哪裡開始,但無法找到字段的終點,意即缺少第二個引號,則會產生「unterminated string literal」的錯誤。如果你的程式出現了這樣的錯誤,檢查並確認自己的字串是否遺漏了任何引號。</li>
 <li>如果你先定義了變數 <code>string</code> ,則以下程式碼可以正常運作。馬上來試試看:
  <pre class="brush: js notranslate">let badString = string;
badString;</pre>
  <code>badString</code> 會被設定跟 <code>string</code> 具有一樣的值。</li>
</ol>

<h3 id="單引號與雙引號">單引號與雙引號</h3>

<ol>
 <li>在 JavaScript 中,你可以選擇用單引號或雙引號來包住字串。兩種方式都可行:
  <pre class="brush: js notranslate">let sgl = 'Single quotes.';
let dbl = "Double quotes";
sgl;
dbl;</pre>
 </li>
 <li>兩種之間的差異非常小,取決於你個人的習慣與喜好。你可以選擇一種,並且固定使用它。交互使用兩種方式,容易造成混亂。特別是當你使用兩種不同的引號包住一個字串!這會導致錯誤回傳:
  <pre class="brush: js example-bad notranslate">let badQuotes = 'What on earth?";</pre>
 </li>
 <li>瀏覽器會認為字串並沒有結束,沒有作為包住字串的引號,是可以出現在字串裡面的。看看下面的例子,兩種都是可行的:
  <pre class="brush: js notranslate">let sglDbl = 'Would you eat a "fish supper"?';
let dblSgl = "I'm feeling blue.";
sglDbl;
dblSgl;</pre>
 </li>
 <li>但是,字串中不可以再使用那個作為包住字串的引號。以下的程式行會出錯,因為瀏覽器無法判斷字串的結尾:
  <pre class="brush: js example-bad notranslate">let bigmouth = 'I've got no right to take my place...';</pre>
  This leads us very nicely into our next subject.</li>
</ol>

<h3 id="字串中的跳脫字元(Escaping_characters)">字串中的跳脫字元(Escaping characters)</h3>

<p>要修復先前出錯的那一行程式碼,我們需要解決引號的問題。跳脫字元(Escaping characters)的意思是我們需要確保它們被辨識為文字,而非程式碼本身。在 JavaScript 中,我們在字元的前面放一個反斜線解決這個問題。試試看這個:</p>

<pre class="brush: js notranslate">let bigmouth = 'I\'ve got no right to take my place...';
bigmouth;</pre>

<p>這是可行的!你可以用一樣的方法跳脫其他字元,例如 <code>\"</code>。除此之外,還有一些特殊方法。更詳細的部分,請參閱<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Escape_notation">跳脫符號</a> 。</p>

<h2 id="連接字串(Concatenating_strings)">連接字串(Concatenating strings)</h2>

<ol>
 <li>連接(Concatenate)是一個新潮的程式用語。在 JavaScript 中,使用加號(+)將字串連接;這也是我們做數字相加的方式。但在這個狀況下,它有不同的作用。讓我們在 console 中示範:</li>
 <li>
  <pre class="brush: js notranslate">let one = 'Hello, ';
let two = 'how are you?';
let joined = one + two;
joined;</pre>
  這邊的結果是 <code>joined</code>  這個變數中,有了 「Hello, how are you?」這個值。</li>
 <li>在上一個範例中,我們只連接了兩個字串。但只要你在兩個字串之間加上 <code>+</code> ,那你要連接幾個都可以。試試看這個:
  <pre class="brush: js notranslate">let multiple = one + one + one + one + two;
multiple;</pre>
 </li>
 <li>你也可以結合變數和字串。試試看這個:
  <pre class="brush: js notranslate">let response = one + 'I am fine — ' + two;
response;</pre>
 </li>
</ol>

<div class="note">
<p><strong>Note</strong>: 當你輸入一個字串在你的程式碼中,並用單引號或雙引號將它括起來,它稱為<strong>字串文字</strong><strong>string literal</strong>)。</p>
</div>

<h3 id="Concatenation_in_context">Concatenation in context</h3>

<p>讓我們看看實際運用連接字串的例子——以下是這堂課中稍早的範例:</p>

<pre class="brush: html notranslate">&lt;button&gt;Press me&lt;/button&gt;</pre>

<pre class="brush: js notranslate">const button = document.querySelector('button');

button.onclick = function() {
  let name = prompt('What is your name?');
  alert('Hello ' + name + ', nice to see you!');
}</pre>

<p>{{ EmbedLiveSample('Concatenation_in_context', '100%', 50, "", "", "hide-codepen-jsfiddle") }}</p>

<p>在程式第四行我們用了 {{domxref("window.prompt()", "window.prompt()")}} 這個函式,可以要求使用者透過彈出的對話框去回答問題,並將使用者輸入的文字儲存在給訂的變數內(在這個例子中就是 <code>name</code>)。接著我們在第五行用了 {{domxref("window.alert()", "window.alert()")}} 函式,顯示另一個彈出視窗,以連接的方式將兩段字串文字以及 <code>name</code> 這個變數結合成一個字串。</p>

<h3 id="數字_vs._字串">數字 vs. 字串</h3>

<ol>
 <li>那麼我們將字串和數字連接會發生什麼事呢?讓我們在console中試試看:
  <pre class="brush: js notranslate">'Front ' + 242;
</pre>
  或許你預期會跑出錯誤訊息,但看來依然正常運作。若將字串表示成數字似乎不太合理,但將數字表示成字串看來是可行的,所以瀏覽器便會巧妙地將數字轉換成字串,並將這兩個字串連接在一起。</li>
 <li>你也可以用兩個數字做這個例子 — 將這兩個數字包在引號中強制將它們轉換成字串。試試看(並使用typeof這個運算子去檢查變數是數字或字串):
  <pre class="brush: js notranslate">let myDate = '19' + '67';
typeof myDate;</pre>
 </li>
 <li>如果你想轉換數字變數成字串,但不要更動到原本的變數;或是想轉換字串變數成數字,也不要更動到原本的變數,你可以使用以下兩種方式:
  <ul>
   <li>物件 {{jsxref("Number")}} 會將欲處理的變數轉換成數字(如果可行的話)。試試以下例子:
    <pre class="brush: js notranslate">let myString = '123';
let myNum = Number(myString);
typeof myNum;</pre>
   </li>
   <li>另一方面,也有 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString">toString()</a></code> 方法能夠讓數字轉換為相等的字串。試試看:
    <pre class="brush: js notranslate">let myNum = 123;
let myString = myNum.toString();
typeof myString;</pre>
   </li>
  </ul>
  這些結構在某些情況相當好用。舉例來說:如果使用者在文字表單中輸入了一個數字,這個數字將會是字串格式。而若想要把這個數字加上另一個數字,那你會希望它是數字格式(才能做數字相加),所以可以使用 <code>Number()</code> 來處理這個情況。可以看看實際案例:<a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/first-splash/number-guessing-game.html#L61">猜數字遊戲, 第61行</a></li>
</ol>

<h2 id="模版字符串Template_literals">模版字符串(Template literals)</h2>

<p>另一種你會遇上的字串語法是<strong>模版字符串(template literals)</strong> (也稱做模版字串 template strings)。這是一種更新的語法提供更彈性、簡單的方式去理解字串。</p>

<div class="blockIndicator note">
<p><strong>Note</strong>: 嘗試在你的瀏覽器上測試下面的範例,來看看會得到什麼結果。</p>
</div>

<p>將標準字串轉變為模版字符串,你需要將引號 (<code>' '</code>, or <code>" "</code>) 換為重音符 (backtick characters (<code>` `</code>) ),接著來看一個簡單的例子:</p>

<pre class="brush: js notranslate">let song = 'Fight the Youth';</pre>

<p>轉換成模版字符串會像這樣子:</p>

<pre class="brush: js notranslate">song = `Fight the Youth`;</pre>

<p>如果我們想要連接字串,或是將算式的結果包含在裡面,用傳統的字串去寫會很瑣碎且麻煩:</p>

<pre class="brush: js notranslate">let score = 9;
let highestScore = 10;
let output = 'I like the song "' + song + '". I gave it a score of ' + (score/highestScore * 100) + '%.';</pre>

<p>模版字符串能大量簡化這串程式碼:</p>

<pre class="brush: js notranslate">output = `I like the song "${ song }". I gave it a score of ${ score/highestScore * 100 }%.`;</pre>

<p>全部一串都只需要包含在一對重音符號裡,不再需要切開、合起一堆字串碎片。<br>
 當你想要包含變數或者算式在字串裡時,你只需要將它放在 <em>佔位符 </em><code>${ } </code>裡。</p>

<p>你能將複雜的算式包含在模版字符串裡,舉個例子:</p>

<pre class="brush: js notranslate">let examScore = 45;
let examHighestScore = 70;
examReport = `You scored ${ examScore }/${ examHighestScore } (${ Math.round((examScore/examHighestScore*100)) }%). ${ examScore &gt;= 49 ? 'Well done, you passed!' : 'Bad luck, you didn\'t pass this time.' }`;
</pre>

<ul>
 <li>前兩個佔位符非常好理解,字串裡只包含了單一值。</li>
 <li>第三個計算了一個百分比的結果且四捨五入進整數。</li>
 <li>第四個使用了三元運算符來檢查分數是否高於指定分數且印出一個通過或著失敗的訊息結果。</li>
</ul>

<p>另一個可以注意的點是,如果你想要將傳統字串拆分成多行,你需要加上一個斷行字母, <code>\n</code></p>

<pre class="brush: js notranslate">output = 'I like the song "' + song + '".\nI gave it a score of ' + (score/highestScore * 100) + '%.';</pre>

<p>模版字符串保留了程式碼中的斷行方式,所以不再需要使用斷行字母。<br>
 這樣也能達到相同的結果:</p>

<pre class="brush: js notranslate">output = `I like the song "${ song }".
I gave it a score of ${ score/highestScore * 100 }%.`;</pre>

<p>我們建議你盡可能習慣使用模版字符串。現今流行的瀏覽器都能完好的支援它,只有一個地方你能發現它並不支援外: Internet Explorer。<br>
 我們有許多的例子仍然使用目前標準的字串語法,但我們未來將會加入更多模版字符串的應用。</p>

<p>來我們的<a href="/en-US/docs/Web/JavaScript/Reference/Template_literals">Template literals</a> 相關頁面看看更多的範例與進階的特色細節。</p>

<h2 id="測試您的技能!">測試您的技能!</h2>

<p>你已到達文章的結尾了,但你能記得最重要的資訊嗎?<br>
 在繼續學習之前,你可以找些難一點的測驗,來檢測你有記得這些知識 —  <a href="/en-US/docs/Learn/JavaScript/First_steps/Test_your_skills:_Strings">Test your skills: Strings</a>. 記住,接下來的文章也需要這些知識,所以你可能想先看看。</p>

<h2 id="結語">結語</h2>

<p>以上是JavaScript中基礎的字串觀念。下個文章中,我們會依循這些概念並試試一些適用於字串的內建方法,進而運用這些方法讓字串能照我們想要的方式呈現。</p>

<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps")}}</p>

<h2 id="在這個學習模組中">在這個學習模組中</h2>

<ul>
 <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/What_is_JavaScript">什麼是 JavaScript?</a></li>
 <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/A_first_splash">和 JavaScript 的第一次接觸</a></li>
 <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/What_went_wrong">什麼出錯了?JavaScript 的疑難排解(除錯)</a></li>
 <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Variables">儲存你需要的資訊 — 變數</a></li>
 <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Math">JavaScript 的基本運算— 數字 與 運算子</a></li>
 <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Strings">處理文字 - JavaScript 的字串</a></li>
 <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Useful_string_methods">有用的字串方法</a></li>
 <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Arrays">陣列</a></li>
 <li><a href="/zh-TW/docs/Learn/JavaScript/First_steps/Silly_story_generator">附錄:笑話產生器</a></li>
</ul>