JavaScript series
This chapter talks about trivial and miscellaneous issues in JavaScript that I don’t know where to put them
If you are looking forward to the support and suggestions of everyone to complete the series.
A. Math object
Math is an object available in JS, containing a number of constants and mathematical functions. You can use the Math object directly without creating it.
1. Math constants
Inside Math there are mathematical constants as attributes.
1 2 3 4 5 6 7 8 9 | Math <span class="token punctuation">.</span> <span class="token constant">E</span> <span class="token punctuation">;</span> Math <span class="token punctuation">.</span> <span class="token constant">PI</span> <span class="token punctuation">;</span> Math <span class="token punctuation">.</span> <span class="token constant">SQRT2</span> <span class="token punctuation">;</span> Math <span class="token punctuation">.</span> <span class="token constant">SQRT1_2</span> <span class="token punctuation">;</span> Math <span class="token punctuation">.</span> <span class="token constant">LN2</span> <span class="token punctuation">;</span> Math <span class="token punctuation">.</span> <span class="token constant">LN10</span> <span class="token punctuation">;</span> Math <span class="token punctuation">.</span> <span class="token constant">LOG2E</span> <span class="token punctuation">;</span> Math <span class="token punctuation">.</span> <span class="token constant">LOG10E</span> <span class="token punctuation">;</span> |
The names of constants are all capitalized, and they cannot be changed.
2. Math methods
Some important methods of Math are as follows.
1 2 3 4 5 6 | Math <span class="token punctuation">.</span> <span class="token function">abs</span> <span class="token punctuation">(</span> number <span class="token punctuation">)</span> <span class="token punctuation">;</span> Math <span class="token punctuation">.</span> <span class="token function">pow</span> <span class="token punctuation">(</span> base <span class="token punctuation">,</span> exp <span class="token punctuation">)</span> <span class="token punctuation">;</span> Math <span class="token punctuation">.</span> <span class="token function">exp</span> <span class="token punctuation">(</span> number <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token comment">// e^x</span> Math <span class="token punctuation">.</span> <span class="token function">sqrt</span> <span class="token punctuation">(</span> number <span class="token punctuation">)</span> <span class="token punctuation">;</span> Math <span class="token punctuation">.</span> <span class="token function">cbrt</span> <span class="token punctuation">(</span> number <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token comment">// Cubic root - căn bậc 3</span> |
Functions to round numbers
1 2 3 4 5 6 7 8 | Math <span class="token punctuation">.</span> <span class="token function">round</span> <span class="token punctuation">(</span> number <span class="token punctuation">)</span> <span class="token punctuation">;</span> Math <span class="token punctuation">.</span> <span class="token function">floor</span> <span class="token punctuation">(</span> number <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token comment">// Làm tròn xuống, kể cả số âm</span> Math <span class="token punctuation">.</span> <span class="token function">ceil</span> <span class="token punctuation">(</span> number <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token comment">// Làm tròn lên, kể cả số âm</span> Math <span class="token punctuation">.</span> <span class="token function">trunc</span> <span class="token punctuation">(</span> number <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token comment">// Làm tròn về số nguyên, cắt bỏ phần thập phân</span> |
The function random a real number from 0 to 1.
1 2 | Math <span class="token punctuation">.</span> <span class="token function">random</span> <span class="token punctuation">(</span> <span class="token punctuation">)</span> <span class="token punctuation">;</span> |
The function finds max, min of any number of numbers.
1 2 3 | Math <span class="token punctuation">.</span> <span class="token function">max</span> <span class="token punctuation">(</span> n1 <span class="token punctuation">,</span> n2 <span class="token punctuation">,</span> n3 <span class="token punctuation">,</span> <span class="token operator">...</span> <span class="token punctuation">)</span> <span class="token punctuation">;</span> Math <span class="token punctuation">.</span> <span class="token function">min</span> <span class="token punctuation">(</span> n1 <span class="token punctuation">,</span> n2 <span class="token punctuation">,</span> n3 <span class="token punctuation">,</span> <span class="token operator">...</span> <span class="token punctuation">)</span> <span class="token punctuation">;</span> |
For max, min a sequence of numbers, use the apply()
method to pass the array as follows.
1 2 3 | <span class="token keyword">let</span> a <span class="token operator">=</span> <span class="token punctuation">[</span> <span class="token number">2</span> <span class="token punctuation">,</span> <span class="token number">5</span> <span class="token punctuation">,</span> <span class="token number">2</span> <span class="token punctuation">,</span> <span class="token number">9</span> <span class="token punctuation">]</span> <span class="token punctuation">;</span> <span class="token keyword">let</span> max <span class="token operator">=</span> Math <span class="token punctuation">.</span> <span class="token function">max</span> <span class="token punctuation">.</span> <span class="token function">apply</span> <span class="token punctuation">(</span> <span class="token keyword">null</span> <span class="token punctuation">,</span> a <span class="token punctuation">)</span> <span class="token punctuation">;</span> |
Learn more about apply()
in the JavaScript function chapter.
B. Error handling
When the code runs, there may be unexpected errors occur. Some errors can be found and fixed, such as the case of wrong code, users do not enter data, divide by 0, … it can be quickly fixed. However, there are some unexpected errors such as network errors, hardware errors, server rejection, … it is impossible to check them all.
Such errors are growing more and more unpredictable, so the way to catch errors by anticipating cases and fixing them as before is no longer effective. Therefore, the concepts of exception (exception) and exception handling (exception handling) are introduced.
In JS, the exception is called error, this concept is equivalent to the exception in other languages.
1. Try catch finally
1 2 3 4 5 6 7 8 | <span class="token keyword">try</span> <span class="token punctuation">{</span> <span class="token operator">...</span> <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span> err <span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token operator">...</span> <span class="token punctuation">}</span> <span class="token keyword">finally</span> <span class="token punctuation">{</span> <span class="token operator">...</span> <span class="token punctuation">}</span> |
The try catch finally
error structure is introduced to catch all kinds of errors that arise when running certain code. The structure consists of 3 parts as above, of which the finally part can be omitted:
- The
try
block: contains pieces of code that can cause errors. catch
block: when an error occurs, the current code is stopped and this block is executed to handle the received error (for example, informing the user for example).catch
usually takes a parameter namede
orerr
, representing the error thrown (it’s okay if not).- The
finally
: block is always executed, with or without errors.
Flow of try catch finally
from top to bottom. If the code in try
has an error, then jump right into the catch
to process. If the try
has no error then the catch
block will be ignored. Finally, if the finally
block exists, the code will be executed in this block.
2. Throw an error
Used to throw a custom error, this error can be anything, such as a number (error code), a string (error message) or an error object (discussed later).
1 2 3 | <span class="token keyword">throw</span> <span class="token string">'Input is not valid'</span> <span class="token punctuation">;</span> <span class="token keyword">throw</span> <span class="token number">404</span> <span class="token punctuation">;</span> |
Throw is often used in functions, to throw an error. And if this function is called in the above try
block, if an error is thrown by the function then the catch
will catch it.
Add an example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <span class="token keyword">function</span> <span class="token function">checkAge</span> <span class="token punctuation">(</span> <span class="token parameter">age</span> <span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token keyword">if</span> <span class="token punctuation">(</span> age <span class="token operator"><</span> <span class="token number">18</span> <span class="token punctuation">)</span> <span class="token keyword">throw</span> <span class="token string">'You must be at least 18 years old :D'</span> <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token operator">...</span> <span class="token keyword">try</span> <span class="token punctuation">{</span> <span class="token comment">// Input age</span> <span class="token function">checkAge</span> <span class="token punctuation">(</span> <span class="token number">16</span> <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token comment">// :)</span> console <span class="token punctuation">.</span> <span class="token function">log</span> <span class="token punctuation">(</span> <span class="token string">'Oh, welcome to X'</span> <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span> e <span class="token punctuation">)</span> <span class="token punctuation">{</span> console <span class="token punctuation">.</span> <span class="token function">log</span> <span class="token punctuation">(</span> <span class="token string">'Chưa đủ tuổi thì biến đi nha, ahihi'</span> <span class="token punctuation">)</span> <span class="token punctuation">;</span> console <span class="token punctuation">.</span> <span class="token function">log</span> <span class="token punctuation">(</span> e <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token comment">// You must be at least 18 years old :D</span> <span class="token punctuation">}</span> |
The above code uses the user’s age, and uses checkAge()
to check. Instead of the previous test the function will return a boolean, true is ok and false is not, but here we will use the error instead.
If age
less than 18, checkAge()
will throw an error, You must be...
The try
block when detecting an error will stop immediately, and jump over the catch
. This unit takes an error into the parameter e
, and prints it to the console screen.
In contrast, age
greater than 18 has no error thrown, the commands in try
are carried forward and finally notified Oh, welcome to X
3. Nested try catch
The try catch finally
block can be nested as follows. And should refrain from writing such nested.
1 2 3 4 5 6 7 8 9 10 11 12 | <span class="token keyword">try</span> <span class="token punctuation">{</span> <span class="token keyword">try</span> <span class="token punctuation">{</span> <span class="token function">checkAge</span> <span class="token punctuation">(</span> <span class="token number">16</span> <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token comment">// Các trò XYZ bình thường</span> <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span> e1 <span class="token punctuation">)</span> <span class="token punctuation">{</span> console <span class="token punctuation">.</span> <span class="token function">log</span> <span class="token punctuation">(</span> e1 <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token comment">// Những trò ABC, XYZ khác ở đây :)</span> <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span> e2 <span class="token punctuation">)</span> <span class="token punctuation">{</span> console <span class="token punctuation">.</span> <span class="token function">log</span> <span class="token punctuation">(</span> e2 <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token punctuation">}</span> |
This makes another issue arise, when the error checkAge()
which catch
block will catch
that error. As above code, only the catch(e1)
block catch(e1)
will receive and handle the error. So, only the user can access những trò XYZ bình thường
but can continue with những trò ABC, XYZ khác
.
So, if you want both blocks to receive errors, then how. That is, if the internal try
fails, the external try
also receives the error and stops at the same time. That is to ensure safety.
At this point, the throw
command will take advantage of its second effect, which is to forward the error to the next error capture block. Modify the code as follows.
1 2 3 4 5 6 7 8 9 10 11 12 13 | <span class="token keyword">try</span> <span class="token punctuation">{</span> <span class="token keyword">try</span> <span class="token punctuation">{</span> <span class="token function">checkAge</span> <span class="token punctuation">(</span> <span class="token number">16</span> <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token comment">// Các trò XYZ bình thường</span> <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span> e1 <span class="token punctuation">)</span> <span class="token punctuation">{</span> console <span class="token punctuation">.</span> <span class="token function">log</span> <span class="token punctuation">(</span> e1 <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token keyword">throw</span> e1 <span class="token punctuation">;</span> <span class="token comment">// Hereeeee</span> <span class="token punctuation">}</span> <span class="token comment">// Những trò ABC, XYZ khác ở đây :)</span> <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span> e2 <span class="token punctuation">)</span> <span class="token punctuation">{</span> console <span class="token punctuation">.</span> <span class="token function">log</span> <span class="token punctuation">(</span> e2 <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token punctuation">}</span> |
Errors when handled in catch(e1)
completed will be thrown (forward) upwards for the large outside try catch
block to know, and from there catch(e2)
will be received and processed.
4. Error object
JS has a number of error objects available, each containing two name and message attributes of string type to describe an error. The functions available in JS will throw an error object whenever an error occurs.
1 2 3 4 5 6 | <span class="token keyword">try</span> <span class="token punctuation">{</span> <span class="token function">abc</span> <span class="token punctuation">(</span> <span class="token number">10</span> <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span> e <span class="token punctuation">)</span> <span class="token punctuation">{</span> console <span class="token punctuation">.</span> <span class="token function">log</span> <span class="token punctuation">(</span> e <span class="token punctuation">.</span> name <span class="token punctuation">,</span> e <span class="token punctuation">.</span> message <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token punctuation">}</span> |
The above code shows an “abc does not exist” error, and the error thrown by JS is named ReferenceError
and the message is abc is not defined
.
Some commonly available error objects:
RangeError
: exceeds allowed rangeTypeError
: wrong type, or access to null (similar to NullPointerException in Java)SyntaxError
: wrong syntaxReferenceError
: undefined,ReferenceError
variable
There are also some other types of error objects. The above errors are standard errors in JS, in addition to non-standard errors (non-standard) depending on the browser type.
C. JSON
1. JSON introduction
JSON (JavaScript Object Notation) is a set of data format syntax, commonly used in storing and exchanging data between clients and servers similar to XML.
JSON has the following characteristics:
- Light-weight (light-weight)
- Self describle: speaking itself of its content, understanding simply reading and understanding immediately
- Highly compatible, regardless of language
JSON and JS
JSON has the same syntax as the JS object, but JSON is essentially just a text, so in addition to JS, there are other languages that can use JSON (directly or through libraries).
Because the structure is similar to the JS object, handling JSON in JS is much easier.
JSON vs XML
Cross domain policy & JSONP
2. JSON syntax
JSON obeys certain rules of writing, just the right rules can be completely processed and error free.
Data pair
Data stored in JSON is paired with key and value similar to property and value in JS. Between key and value are two dots, between pairs are commas.
JSON does not allow comma trailing, meaning that the comma is the last one, while JS still works.
1 2 3 4 | <span class="token punctuation">[</span> <span class="token number">1</span> <span class="token punctuation">,</span> <span class="token number">2</span> <span class="token punctuation">,</span> <span class="token number">3</span> <span class="token punctuation">,</span> <span class="token comment">// Sai</span> <span class="token punctuation">]</span> |
The difference with object syntax in JS is that the JSON key name must always enclose the ""
pair (must be double quotes, do not accept single quotes or anything else).
Data types
JSON accepts values of types:
- Null
- Number
- Boolean
- String: use enclosed double quotes
- Object: put in pair {}, which contains many similar
key: value
pairs - Array: enclose in [], each element is separated by commas
Unlike object, JSON is pure data, so it does not allow types:
- Function
- Date
- Undefined
1 2 3 4 5 6 7 8 9 10 11 | <span class="token punctuation">[</span> <span class="token punctuation">{</span> <span class="token property">"name"</span> <span class="token operator">:</span> <span class="token string">"John"</span> <span class="token punctuation">,</span> <span class="token property">"age"</span> <span class="token operator">:</span> <span class="token number">20</span> <span class="token punctuation">}</span> <span class="token punctuation">,</span> <span class="token punctuation">{</span> <span class="token property">"name"</span> <span class="token operator">:</span> <span class="token string">"Vu"</span> <span class="token punctuation">,</span> <span class="token property">"age"</span> <span class="token operator">:</span> <span class="token number">18</span> <span class="token punctuation">}</span> <span class="token punctuation">]</span> |
The sample JSON above is an array of 2 child objects, each object has two name
and value
properties.
Nested
Data pairs can be nested inside an array or object. Note that when inserted into the object, it must belong to a certain new key, as the following example.
1 2 3 4 5 6 7 8 9 10 11 12 | <span class="token comment">// Không hợp lệ</span> <span class="token punctuation">{</span> <span class="token number">10</span> <span class="token punctuation">,</span> <span class="token comment">// Sai</span> <span class="token punctuation">[</span> <span class="token number">1</span> <span class="token punctuation">,</span> <span class="token number">2</span> <span class="token punctuation">,</span> <span class="token number">3</span> <span class="token punctuation">]</span> <span class="token comment">// Sai</span> <span class="token punctuation">}</span> <span class="token comment">// Hợp lệ</span> <span class="token punctuation">{</span> <span class="token property">"age"</span> <span class="token operator">:</span> <span class="token number">10</span> <span class="token punctuation">,</span> <span class="token property">"data"</span> <span class="token operator">:</span> <span class="token punctuation">[</span> <span class="token number">1</span> <span class="token punctuation">,</span> <span class="token number">2</span> <span class="token punctuation">,</span> <span class="token number">3</span> <span class="token punctuation">]</span> <span class="token punctuation">}</span> |
JSON minify
JSON sometimes you will see it is not written on many lines as above, only one line, no tabs or spaces at all, that is JSON minified to reduce the size down.
1 2 3 4 5 6 7 8 9 | <span class="token comment">// Chưa minify</span> <span class="token punctuation">{</span> <span class="token property">"name"</span> <span class="token operator">:</span> <span class="token string">"John"</span> <span class="token punctuation">,</span> <span class="token property">"age"</span> <span class="token operator">:</span> <span class="token number">20</span> <span class="token punctuation">}</span> <span class="token comment">// Đã minify</span> <span class="token punctuation">{</span> <span class="token property">"name"</span> <span class="token operator">:</span> <span class="token string">"John"</span> <span class="token punctuation">,</span> <span class="token property">"age"</span> <span class="token operator">:</span> <span class="token number">20</span> <span class="token punctuation">}</span> |
Either way, it is valid because it is true to the JSON structure, but the minified segment is smaller and helps to consume bandwidth when transmitted, so it is often used.
The opposite of minify is pretty print, which makes the reduced JSON segment more beautiful.
3. JSON handling
JSON processing in JS is extremely easy, only consists of two operations:
- Parse: from string JSON to an object in JS
- Stringify: from object to JSON string
The above two operations correspond to the two methods of the JSON object.
JSON.parse method
1 2 3 | <span class="token keyword">let</span> json <span class="token operator">=</span> <span class="token string">'{"name":"John","age":20}'</span> <span class="token punctuation">;</span> <span class="token keyword">let</span> obj <span class="token operator">=</span> <span class="token constant">JSON</span> <span class="token punctuation">.</span> <span class="token function">parse</span> <span class="token punctuation">(</span> json <span class="token punctuation">)</span> <span class="token punctuation">;</span> |
Parse the JSON string into an object. Minify JSON string or not is okay, just the syntax is successful parse.
JSON.stringify method
Generate JSON string from object.
1 2 3 4 5 6 | <span class="token keyword">let</span> obj <span class="token operator">=</span> <span class="token punctuation">{</span> name <span class="token operator">:</span> <span class="token string">'John'</span> <span class="token punctuation">,</span> age <span class="token operator">:</span> <span class="token number">20</span> <span class="token punctuation">}</span> <span class="token punctuation">;</span> <span class="token keyword">let</span> json <span class="token operator">=</span> <span class="token constant">JSON</span> <span class="token punctuation">.</span> <span class="token function">stringify</span> <span class="token punctuation">(</span> obj <span class="token punctuation">)</span> <span class="token punctuation">;</span> |
Note that if objects contain Date, undefined, or method properties, they will not be added to the JSON string.
By default, the generated JSON string has been minified, modified as follows to make the JSON string more beautiful and readable.
1 2 | <span class="token keyword">let</span> json <span class="token operator">=</span> <span class="token constant">JSON</span> <span class="token punctuation">.</span> <span class="token function">stringify</span> <span class="token punctuation">(</span> obj <span class="token punctuation">,</span> <span class="token keyword">null</span> <span class="token punctuation">,</span> <span class="token number">2</span> <span class="token punctuation">)</span> <span class="token punctuation">;</span> |
The third parameter above is the number of spaces used for indents. The second parameter is a replacer, but is rarely used, so it is set to null.
D. Regex
1. Regex introduction
Regex (regular expression – regexp) is a short text used to describe a pattern to search in text. Instead of searching for a exact string, a search with regex will return results that match the rules that the regex defines.
For example, finding all phone numbers in a long document. Obviously a normal search cannot be done because there is no exact number, only the structure of a 10-digit phone number. Therefore, we use regex /d{10}/g
to find.
Of course, to find exactly, you need to know how to write the symbols of regex properly as required. This section will be discussed more in another post, you can find out more.
2. Regex in JS
String regex
Regex is just a text string with certain rules, so in JS it is also a string. And this regex string is written slightly different from the normal string.
1 2 | <span class="token keyword">let</span> regex <span class="token operator">=</span> <span class="token regex">/d{10}/g</span> <span class="token punctuation">;</span> |
The regex string in JS consists of 2 parts:
- The pattern part (in the
//
pair): defines the regex structure - The flags section (behind the
//
pair): additional options for regex.
When the search with the regex is complete, the result usually returns an array of substrings matching the regex, each matching string called a match.
Check the match
Use the .test()
method to check if a string matches a regex.
1 2 3 | <span class="token keyword">let</span> regex <span class="token operator">=</span> <span class="token regex">/d{10}/g</span> <span class="token punctuation">;</span> regex <span class="token punctuation">.</span> <span class="token function">test</span> <span class="token punctuation">(</span> <span class="token string">'So dien thoai cua 23412 la 0234321345'</span> <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token comment">// true</span> |
It only takes a portion of the regex match. If you want the whole string to match, without any redundancy, use the first anchor directive ^
and the end $
for the regex.
This method is often used to check if the user input is valid or not. For example, check if a string is an email, exactly when it matches the regex string describing the email (search on google ).
Get the match list
Use the .match()
method to get a list of match .match()
in a string.
1 2 3 4 | <span class="token keyword">let</span> s <span class="token operator">=</span> <span class="token string">'Hello, I am 234 and my name is 334'</span> <span class="token punctuation">;</span> <span class="token keyword">let</span> a <span class="token operator">=</span> s <span class="token punctuation">.</span> <span class="token function">match</span> <span class="token punctuation">(</span> <span class="token regex">/d/g</span> <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token comment">// a = ['234', '334']</span> |
Regex /d/g
finds all (flag g
) numbers d
in the given string s. The result is an array of 2 elements as above.
Regex in functions
Some functions and methods in JS support regex, for example, the split()
method of string is used to cut strings into multiple substrings, separated by separators.
For example, separating words in a string is as follows.
1 2 3 4 | <span class="token keyword">let</span> s <span class="token operator">=</span> <span class="token string">'Toi yeu Viet Nam'</span> <span class="token punctuation">;</span> <span class="token keyword">let</span> a <span class="token operator">=</span> s <span class="token punctuation">.</span> <span class="token function">split</span> <span class="token punctuation">(</span> <span class="token string">' '</span> <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token comment">// Cách cũ, separator là khoảng trắng</span> <span class="token comment">// a = ['Toi', 'yeu', '', '', 'Viet', '', 'Nam']</span> |
Using the old method will only cut in a single space, so the result is not as expected. Now is the time for regex to take effect, because split()
function supports regex as separator. We correct the code as follows.
1 2 3 4 | <span class="token keyword">let</span> s <span class="token operator">=</span> <span class="token string">'Toi yeu Viet Nam'</span> <span class="token punctuation">;</span> <span class="token keyword">let</span> a <span class="token operator">=</span> s <span class="token punctuation">.</span> <span class="token function">split</span> <span class="token punctuation">(</span> <span class="token regex">/s+/</span> <span class="token punctuation">)</span> <span class="token punctuation">;</span> <span class="token comment">// Cách mới</span> <span class="token comment">// a = ['Toi', 'yeu', 'Viet', 'Nam']</span> |
The result is exactly what you want, no matter how much distance the word has.
Explain regex /s+/
above a bit:
- Token
s
is for space only. - The
+
sign indicates that the preceding character can repeat 1 or more times.
In addition to the split()
function as above, JS has many other functions and methods that support regex as parameters like .search()
, replace()
, … can learn more.