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
|
---
title: Handling text — strings in JavaScript
slug: Learn/JavaScript/First_steps/Strings
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"><span style="background-color: #f6d5d9;">Tiếp theo chúng ta sẽ cùng tập trung vào</span> chuỗi (string) — Trong lập trình chuỗi là một phần nhỏ của văn bản. Trong bài viết này chúng ta sẽ cùng tìm hiểu tất cả các đặc điểm chúng mà bạn cần phải biết về chuỗi khi học JavaScript, như là tạo chuỗi, escaping quotes trong chuỗi và kết hợp chuỗi lại với nhau.</p>
<table class="learn-box standard-table">
<tbody>
<tr>
<th scope="row">Yêu cầu:</th>
<td>
<p>Trình độ máy tính cơ bản, có hiểu biết cơ bản về HTML, CSS và JavaScript.</p>
</td>
</tr>
<tr>
<th scope="row">Mục tiêu:</th>
<td>
<p>Làm quen với những thứ cơ bản của chuỗi trong Javascript.</p>
</td>
</tr>
</tbody>
</table>
<h2 id="Sức_mạnh_của_từ_ngữ">Sức mạnh của từ ngữ</h2>
<p>Từ ngữ rất quan trọng với con người - Chúng là một phần của giao tiếp. Bởi vì Web được tạo nên từ một lượng lớn văn bản là vật trung gian giúp con người có thể giao tiếp và chia sẻ thông tin, sẽ hữu ích hơn nếu ta có thể làm chủ được toàn bộ từ ngữ xuất hiện trong nó. {{glossary("HTML")}} cung cấp cấu trúc và định nghĩa cho văn bản, {{glossary("CSS")}} cho phép ta có thể tạo kiểu một cách tỷ mỉ cho nó và JavaSript chứa một lượng các tính năng giúp cho việc thao tác lên văn bản, tạo những tin nhắn trang trọng tùy ý, biểu thị đúng nhãn văn bản khi cần thiết, sắp xếp thuận ngữ theo thứ tự mong muốn và nhiều hơn nữa.</p>
<p>Khá nhiều những chương trình mà chúng tôi đã giới thiệu với bạn trong khóa học này, đã có liên quan tới vài việc thao tác lên chuỗi.</p>
<h2 id="Chuỗi_—_Khái_niệm_cơ_bản">Chuỗi — Khái niệm cơ bản</h2>
<p>Chuỗi có vẻ tương tự với số khi ta mới lướt qua, nhưng khi bạn đào sâu hơn, bạn sẽ bắt đầu thấy một số sự khác biệt đáng lưu tâm. Cùng bắt đầu với việc nhập một vài dòng vào console để làm quen nhé. Chúng tôi đã cung cấp một console bên dưới (Bạn có thể mở <a href="https://mdn.github.io/learning-area/javascript/introduction-to-js-1/variables/index.html">console này</a> ở một tab hoặc cửa sổ khác, hoặc sử dụng <a href="/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">console của trình duyệt</a> ở chế độ developer (browser developer console) nếu bạn thích).</p>
<div class="hidden">
<h6 id="Hidden_code">Hidden code</h6>
<pre class="brush: html"><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript console</title>
<style>
* {
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;
}
</style>
</head>
<body>
</body>
<script>
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 = '>';
inputDiv.appendChild(inputPara);
inputDiv.appendChild(inputForm);
document.body.appendChild(inputDiv);
if(document.querySelectorAll('div').length > 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();
</script>
</html></pre>
</div>
<p>{{ EmbedLiveSample('Hidden_code', '100%', 300, "", "", "hide-codepen-jsfiddle") }}</p>
<h3 id="Creating_a_string">Creating a string</h3>
<ol>
<li>To start with, enter the following lines:
<pre class="brush: js">var string = 'The revolution will not be televised.';
string;</pre>
Just like we did with numbers, we are declaring a variable, initializing it with a string value, and then returning the value. The only difference here is that when writing a string, you need to surround the value with quotes.</li>
<li>If you don't do this, or miss one of the quotes, you'll get an error. Try entering the following lines:
<pre class="brush: js example-bad">var badString = This is a test;
var badString = 'This is a test;
var badString = This is a test';</pre>
These lines don't work because any text without quotes around it is assumed to be a variable name, property name, reserved word, or similar. If the browser can't find it, then an error is raised (e.g. "missing ; before statement"). If the browser can see where a string starts, but can't find the end of the string, as indicated by the 2nd quote, it complains with an error (with "unterminated string literal"). If your program is raising such errors, then go back and check all your strings to make sure you have no missing quote marks.</li>
<li>The following will work if you previously defined the variable <code>string</code> — try it now:
<pre class="brush: js">var badString = string;
badString;</pre>
<code>badString</code> is now set to have the same value as <code>string</code>.</li>
</ol>
<h3 id="Single_quotes_vs._double_quotes">Single quotes vs. double quotes</h3>
<ol>
<li>In JavaScript, you can choose single quotes or double quotes to wrap your strings in. Both of the following will work okay:
<pre class="brush: js">var sgl = 'Single quotes.';
var dbl = "Double quotes";
sgl;
dbl;</pre>
</li>
<li>There is very little difference between the two, and which you use is down to personal preference. You should choose one and stick to it, however; differently quoted code can be confusing, especially if you use the different quotes on the same string! The following will return an error:
<pre class="brush: js example-bad">var badQuotes = 'What on earth?";</pre>
</li>
<li>The browser will think the string has not been closed, because the other type of quote you are not using to contain your strings can appear in the string. For example, both of these are okay:
<pre class="brush: js">var sglDbl = 'Would you eat a "fish supper"?';
var dblSgl = "I'm feeling blue.";
sglDbl;
dblSgl;</pre>
</li>
<li>However, you can't include the same quote mark inside the string if it's being used to contain them. The following will error, as it confuses the browser as to where the string ends:
<pre class="brush: js example-bad">var 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_in_a_string">Escaping characters in a string</h3>
<p>To fix our previous problem code line, we need to escape the problem quote mark. Escaping characters means that we do something to them to make sure they are recognized as text, not part of the code. In JavaScript, we do this by putting a backslash just before the character. Try this:</p>
<pre class="brush: js">var bigmouth = 'I\'ve got no right to take my place...';
bigmouth;</pre>
<p>This works fine. You can escape other characters in the same way, e.g. <code>\"</code>, and there are some special codes besides. See <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Escape_notation">Escape notation</a> for more details.</p>
<h2 id="Concatenating_strings">Concatenating strings</h2>
<ol>
<li>Concatenate is a fancy programming word that means "join together". Joining together strings in JavaScript uses the plus (+) operator, the same one we use to add numbers together, but in this context it does something different. Let's try an example in our console.
<pre class="brush: js">var one = 'Hello, ';
var two = 'how are you?';
var joined = one + two;
joined;</pre>
The result of this is a variable called <code>joined</code>, which contains the value "Hello, how are you?".</li>
<li>In the last instance, we just joined two strings together, but you can do as many as you like, as long as you include a <code>+</code> between each one. Try this:
<pre class="brush: js">var multiple = one + one + one + one + two;
multiple;</pre>
</li>
<li>You can also use a mix of variables and actual strings. Try this:
<pre class="brush: js">var response = one + 'I am fine — ' + two;
response;</pre>
</li>
</ol>
<div class="note">
<p><strong>Note</strong>: When you enter an actual string in your code, enclosed in single or double quotes, it is called a <strong>string literal</strong>.</p>
</div>
<h3 id="Concatenation_in_context">Concatenation in context</h3>
<p>Let's have a look at concatenation being used in action — here's an example from earlier in the course:</p>
<pre class="brush: html"><button>Press me</button></pre>
<pre class="brush: js">var button = document.querySelector('button');
button.onclick = function() {
var 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>Here we're using a {{domxref("window.prompt()", "window.prompt()")}} function in line 4, which asks the user to answer a question via a popup dialog box then stores the text they enter inside a given variable — in this case <code>name</code>. We then use an {{domxref("window.alert()", "window.alert()")}} function in line 5 to display another popup containing a string we've assembled from two string literals and the <code>name</code> variable, via concatenation.</p>
<h3 id="Numbers_vs._strings">Numbers vs. strings</h3>
<ol>
<li>So what happens when we try to add (or concatenate) a string and a number? Let's try it in our console:
<pre class="brush: js">'Front ' + 242;
</pre>
You might expect this to throw an error, but it works just fine. Trying to represent a string as a number doesn't really make sense, but representing a number as a string does, so the browser rather cleverly converts the number to a string and concatenates the two strings together.</li>
<li>You can even do this with two numbers — you can force a number to become a string by wrapping it in quote marks. Try the following (we are using the <code>typeof</code> operator to check whether the variable is a number or a string):
<pre class="brush: js">var myDate = '19' + '67';
typeof myDate;</pre>
</li>
<li>If you have a numeric variable that you want to convert to a string but not change otherwise, or a string variable that you want to convert to a number but not change otherwise, you can use the following two constructs:
<ul>
<li>The {{jsxref("Number")}} object will convert anything passed to it into a number, if it can. Try the following:
<pre class="brush: js">var myString = '123';
var myNum = Number(myString);
typeof myNum;</pre>
</li>
<li>On the other hand, every number has a method called <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString">toString()</a></code> that will convert it to the equivalent string. Try this:
<pre class="brush: js">var myNum = 123;
var myString = myNum.toString();
typeof myString;</pre>
</li>
</ul>
These constructs can be really useful in some situations. For example, if a user enters a number into a form text field, it will be a string. However, if you want to add this number to something, you'll need it to be a number, so you could pass it through <code>Number()</code> to handle this. We did exactly this in our <a href="https://github.com/mdn/learning-area/blob/master/javascript/introduction-to-js-1/first-splash/number-guessing-game.html#L61">Number Guessing Game, in line 61</a>.</li>
</ol>
<h2 id="Conclusion">Conclusion</h2>
<p>So that's the very basics of strings covered in JavaScript. In the next article we'll build on this, looking at some of the built-in methods available to strings in JavaScript and how we can use them to manipulate our strings into just the form we want.</p>
<p>{{PreviousMenuNext("Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps")}}</p>
<p> </p>
<h2 id="In_this_module">In this module</h2>
<ul>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript">What is JavaScript?</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/A_first_splash">A first splash into JavaScript</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong">What went wrong? Troubleshooting JavaScript</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/Variables">Storing the information you need — Variables</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/Math">Basic math in JavaScript — numbers and operators</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/Strings">Handling text — strings in JavaScript</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods">Useful string methods</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/Arrays">Arrays</a></li>
<li><a href="/en-US/docs/Learn/JavaScript/First_steps/Silly_story_generator">Assessment: Silly story generator</a></li>
</ul>
<p> </p>
|