SoFunction
Updated on 2025-04-07

Extended instance of ES string

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

Unicode notation of characters

ES6 strengthens support for Unicode. JavaScript can use the \\uxxx form to represent a character, where xxxx represents the code point of the character. For example:

("\u0075"); // u

However, this notation is limited to characters whose code points are between \\u0000~\\uFFFF. Characters outside this range must be represented in two double bytes.

("\uD842\uDFB7"); // 𠮷
("\u20BB8"); // 8

This means that if you follow the value exceeding 0xFFFF directly after \\u, for example \\u20BB8, JavaScript will be understood as \\u20BB+8. Since \u20BB is a non-printable character, only a space will be displayed, followed by an 8.

ES6 has made improvements to this point, and the character can be interpreted correctly by putting the code point in braces.

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

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

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

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

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

With this notation, JavaScript has 6 ways to represent a character.

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

Traverser interface

ES6 adds a traverser interface to strings, so that strings can be traversed by for...of loops.

Example:
For example, we loop through the string xkd:

for (let i of 'xkd') {
 (i)
}

Output:

x
k
d

In addition to traversing strings, the biggest advantage of this traverser is that it can identify code points larger than 0xFFFF. Traditional for loops cannot recognize such code points.

Example:

let a = (0x20BB7);

for (let i = 0; i < ; i++) {
 (a[i]);
}

for (let i of a) {
 (i);
}

In the above code, the string a has only one character, but the for loop will think it contains two characters (neither cannot be printed), while the for...of loop will correctly recognize this character.

Use of template strings

In the JavaScript language, if we want to output content, we can usually write it like this:

var name = "Xiake Island";
var age = 10;
("My name is"+ name + ", I'm this year" + age + "It's been a year." );
// Output: My name is Xiake Island, I am 10 years old this year.

This writing method requires the use of a lot of double quotes and plus signs to splice to get the template we need, which is very inconvenient.

In ES6, template strings are provided, you only need to identify the content you want to output in backquotes, and then enclose the variable part with ${}.

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

var name = "Xiake Island";
var age = 10;
( `My name is${name} ,I'm this year${age}It's old。`);

// Output: My name is Xiake Island, I am 10 years old this year.

It is obvious that the syntax is much more concise, and there is no need to use a lot of double quotes and plus signs to splice strings and variables.

Template strings are all represented by backticks, and if we want to use backticks in the template string, we need to use a backslash \\ escape in front.

Example:

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

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

( `Hello\` My name is Xiake Island,
This year3It's old!`);

After executing the code, the following content will be output directly:

Hello`My name is Xiake Island,
 This year3It's old!

Embed variables in template string

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

Example:

var name= "xkd";
(`Hello,${name}`);

// Output: Hello, xkd

However, if the variable in the template string is not declared, an error will be reported.

let content = `Hello, ${name}`;
(content);  // Output: ReferenceError: name is not defined

Since the curly braces inside the template string are executed JavaScript code, if the curly braces inside are a string, they will be output as it is.

let content = `Hello, ${"xkd"}`;
(content); // Output: Hello, xkd

The braces ${} can be placed in any JavaScript expression, which can perform operations, and reference object properties.

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

// Output: a=11, b=31

Calling a function in a template string

Template strings in ES6 have a more powerful function, which is that we can call functions in template strings.

Example:

function show() {
 return "Xiake Island";
}

(`Hello,May I have your name?
Hello,My name is${show()}`);

After executing the code, the output content is as follows:

Hello, what's your name?
Hello, my name is Xiake Island

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

Determine whether substrings are included

JavaScript If you want to determine whether a string contains a substring, you can use the indexOf() method. However, in ES6, three new methods can be added to determine whether a case contains a substring, as shown below:

  • include(): 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:

All three methods can accept two parameters. The first parameter is the string to be searched, and the second parameter is the optional search start position index:

let string = "hello, xkd";

(("hello")); // true
(("x", 7)); // true
(("abc"));  // false

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

Repeat string

A repeat() method has been added in ES6 to return a new string, indicating that the string is repeated as specified times.

Example:

("a".repeat(5)); // Output: aaaaa

If the arguments in the repeat() function are decimals, they are rounded downwards:

("a".repeat(3.1)); // Output: aaa("b".repeat(4.5)); // Output: bbbb("c".repeat(5.9)); // Output: ccccc

If the parameters are decimals between 0 and -1, the rounding operation will be performed. The decimals between 0 and -1 will be rounded to get -0, which is equivalent to repeating zero times:

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

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

("a".repeat("five")); // Output: ""("b".repeat("3"));  // Output: bbb

String completion

There are two new methods for string completion in ES6, as shown below:

  • 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.

These two methods accept two parameters. The first parameter specifies the minimum length of the generated string, and the second parameter is the string used to complete. If no second parameter is specified, the default is filled with spaces.

Example:

("xkd".padStart(5, "o")); // Output: ooxkd("a".padEnd(3, "xkd"));  // Output: axk("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:

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

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

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

It can also be used to complete digits:

("1".padStart(10, "0")); // 0000000001
("2".padEnd(10, "0"));  // 2000000000

This is the end of this article about the extension example of ES6 strings. For more related ES6 string extension content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!