Extended instance of ES6 string

  • 2021-10-15 09:34:33
  • OfStack

In this section, we will learn about the extension of string types in ES6, including the use of new methods for string objects.

Unicode Representation of Characters

ES6 strengthens support for Unicode. In JavaScript, one character can be represented in the form of\\ uxxx, where xxxx represents the code point of the character. For example:


console.log("\u0075"); // u

However, this notation is limited to characters with code points between\\ u0000 ~\\ uFFFF. Characters beyond this range must be represented in the form of two double bytes.


console.log("\uD842\uDFB7"); // 𠮷
console.log("\u20BB8"); // 8

This means that JavaScript is understood as\ u20BB+8 if a value beyond 0xFFFF is followed directly after\\ u, such as\\ u20BB8. Because\\ u20BB is a non-printable character, only one space is displayed, followed by an 8.

ES6 makes an improvement on this point, so that the character can be interpreted correctly by putting the code point in curly braces.


console.log("\u{20BB7}"); // 𠮷

console.log("\u{41}\u{42}\u{43}"); // ABC

let hello = 123;
console.log(hell\u{6F}); // 123

 
console.log('\u{1F680}' === '\uD83D\uDE80'); // true

In the above code, the last example shows that the curly brace notation is equivalent to the 4-byte UTF-16 encoding.

With this notation, JavaScript has six ways to represent one character.


'\z' === 'z' // true
'\172' === 'z' // true
'\x7A' === 'z' // true
'\u007A' === 'z' // true
'\u{7A}' === 'z' // true

Traverser interface

ES 6 adds a traverser interface to strings so that strings can be iterated by for... of.

Example:
For example, we traverse the string xkd:


for (let i of 'xkd') {
 console.log(i)
}

Output:

x
k
d

In addition to traversing strings, the greatest advantage of this traverser is that it can identify code points larger than 0xFFFF, which cannot be recognized by traditional for loop.

Example:


let a = String.fromCodePoint(0x20BB7);

for (let i = 0; i < a.length; i++) {
 console.log(a[i]);
}

for (let i of a) {
 console.log(i);
}

In the above code, the string a has only 1 character, but the for loop will assume that it contains two characters (neither of which is printable), and the for... of loop will correctly recognize this 1 character.

Use of template strings

In JavaScript, if we want to output content, we can usually write as follows:


var name = " Chivalrous Island ";
var age = 10;
console.log(" My name is "+ name + " , I this year " + age + " I'm ten years old. " );
//  Output: My name is Chivalrous Island, and I am this year 10 I'm ten years old. 

This way of writing needs to use a lot of double quotation marks and plus marks to stitch together to get the template we need, which is very inconvenient.

In ES 6, the template string is provided, and you only need to identify the content you want to output with reverse quotation marks, and then enclose the variable part with ${}.

Example:
The above example can be written as follows in template string:


var name = " Chivalrous Island ";
var age = 10;
console.log( ` My name is ${name}  , I this year ${age} I'm ten years old. `);

//  Output: My name is Chivalrous Island, and I am this year 10 I'm ten years old. 

It is obvious that the syntax is much simpler, and there is no need to use a lot of double quotation marks and plus marks to splice strings and variables.

Template strings are all represented by reverse quotation marks, and if we want to use reverse quotation marks in template strings, we need to use a backslash\\ escape in front of them.

Example:


let content = `\`hello\` xkd!`;
console.log(content); //  Output: `hello` xkd!

If you use a template string to represent a multi-line string, all spaces and indentation are retained in the output.


console.log( ` How do you do \`  My name is Knight Island ,
 This year 3 Years old! `);

After executing the code, it will directly output something like this:

Hello, my name is Xiakedao.
I am 3 years old this year!

Embedding variables in template strings

If we want to embed a variable in a template string, the variable needs to be written in ${} to be used properly, otherwise it will be output as a normal string.

Example:


console.log("\uD842\uDFB7"); // 𠮷
console.log("\u20BB8"); // 8

0

However, if the variables in the template string are not declared, an error will be reported.


console.log("\uD842\uDFB7"); // 𠮷
console.log("\u20BB8"); // 8

1

Since the inside of the curly braces of the template string is to execute JavaScript code, if the inside of the curly braces is a string, it will be output as it is.


console.log("\uD842\uDFB7"); // 𠮷
console.log("\u20BB8"); // 8

2

Inside the curly braces ${}, you can put any JavaScript expression, perform operations, and refer to object properties.


var a = 10;
var b = 20;
console.log(`a=${++a} ,  b=${a+b}`);

//  Output: a=11 ,  b=31

Calling a function in a template string

The template string in ES6 has a more powerful function, that is, we can call functions in the template string.

Example:


console.log("\uD842\uDFB7"); // 𠮷
console.log("\u20BB8"); // 8

4

After executing the code, the output is as follows:

Hello, what's your name?
Hello, my name is Xiakedao

If the value in curly braces is not a string, it will be converted to a string according to the rule of 1. For example, if there is an object in curly braces, the toString method of the object will be called by default.

Determine whether to include substrings

JavaScript to determine whether a string contains substrings, you can use the indexOf () method. However, in ES 6, three new methods are added to determine whether a case contains substrings, as follows:

includes (): Returns a Boolean value indicating whether the parameter string was found. startsWith (): Returns a Boolean value indicating whether the parameter string is at the head of the original string. endsWith (): Returns a Boolean value indicating whether the parameter string is at the end of the original string.

Example:

Each of these three methods can take two arguments, the first being the string to search for, and the second being the optional search start index:


console.log("\uD842\uDFB7"); // 𠮷
console.log("\u20BB8"); // 8

5

Note that the return values of the above methods are Boolean values, so if you need to know the position of the substring, you still have to use indexOf () and lastIndexOf () methods.

String duplication

In ES6, a new repeat () method is added to return a new string, which means that the string is repeated a specified number of times.

Example:


console.log("\uD842\uDFB7"); // 𠮷
console.log("\u20BB8"); // 8

6

If the arguments in the repeat () function are decimal, they are rounded down:


console.log("\uD842\uDFB7"); // 𠮷
console.log("\u20BB8"); // 8

7

If the parameter is a decimal between 0 and-1, the rounding operation is performed, and the rounding of the decimal between 0 and-1 results in-0, which is equivalent to repeating zero times:


console.log("a".repeat(-0.1)); //  Output: ""
console.log("b".repeat(-0.9)); //  Output: ""

If the parameter passed in is a string, the string is converted to a number first:


console.log("\uD842\uDFB7"); // 𠮷
console.log("\u20BB8"); // 8

9

String completion

Two new methods for string completion are provided in ES6, as follows:

padStart (): Returns a new string indicating that the original string is completed from the header (left) with the parameter string. padEnd (): Returns a new string, indicating that the original string is completed from the tail (right) with the parameter string.

The two methods take two arguments, the first specifying the minimum length of the generated string, and the second the string to complete. If the second parameter is not specified, it is filled with spaces by default.

Example:


console.log("xkd".padStart(5, "o")); //  Output: ooxkd 
console.log("a".padEnd(3, "xkd"));  //  Output: axk
console.log("b".padStart(3));    //  Output:  b

If the specified length is less than or equal to the length of the original string, the original string is returned:


console.log("hello".padStart(3,"a")); // hello
console.log("hello".padStart(7,"a")); // aahello

If the length of the original string plus the completion string is greater than the specified length, the completion string exceeding the number of digits is truncated:


console.log("hello".padEnd(7,",xkd!"));  // hello,x
console.log("abcde".padEnd(10,"fghijk")); // abcdefghij

It can also be used to complete the number of digits:


console.log("\u{20BB7}"); // 𠮷

console.log("\u{41}\u{42}\u{43}"); // ABC

let hello = 123;
console.log(hell\u{6F}); // 123

 
console.log('\u{1F680}' === '\uD83D\uDE80'); // true

3

Related articles: