Es6 String extension (instance description), es6string

Source: Internet
Author: User

Es6 String extension (instance description), es6string

New Feature: Template string

Traditional string

Let name = "Jacky"; let occupation = "doctor"; // traditional String concatenation let str = "He is" + name + ", he is a" + occupation;

Es6 simple String concatenation

Let name = "Jacky"; let occupation = "doctor"; // template String concatenation let str = 'he is $ {name}, He is a $ {occupation }';

Compare the two pieces of spliced code. The template string makes it unnecessary to use double quotation marks (or single quotation marks) repeatedly. Instead, we use the reverse quotation mark (') instead ('), you do not need to use the plus sign (+) when inserting a variable. Instead, you can put the variable into $.

Pay attention

1. Multi-line strings can be defined.

Traditional multi-line string writing:

let str = "write once ," + "run anywhere";

Template string Syntax:

 let str = `write once , run anywhere`;

You can simply wrap the line, but note that all spaces and inputs are retained in the output. If the console outputs a string 'str', the code changes and the console outputs a new line.

2. arbitrary javascript expressions can be placed in $ {}.

It can be an operation expression in $ {}.

Var a = 1; var B = 2; var str = 'the result is $ {a + B} '; // the addition result is 3.

$ {} Can be an object attribute.

Var obj = {"a": 1, "B": 2}; var str = 'the result is $ {obj. a + obj. b} '; // properties of object obj // result: the result is 3.

$ {} Can be a function call.

Function fn () {return 3;} var str = 'the result is $ {fn ()} '; // call the function fn. the result is 3.

Tag Template

Here, the template refers to the string template mentioned above, which is defined by Reverse quotation marks; while the tag refers to a function, a function that specifically processes the template string.

Var name = "Zhang San"; var height = 1.8; tagFn 'His name is $ {name}, and his height is $ {height} meters. '; // Tag + template string // defines a function as the tag function tagFn (arr, v1, v2) {console. log (arr); // result: ["His name is", ", height", "meters. "] Console. log (v1); // result: Zhang San console. log (v2); // result: 1.8}

The above code is explained in detail in two parts. The first is the tagFn function, which is a custom function. It has three parameters: arr, v1, and v2. The call method of the function tagFn is not the same as in the past. In the past, we used brackets () to indicate the function call and execution. This time, we directly added a template string after the function name, as shown in the following code:

TagFn 'His name is $ {name}, and his height is $ {height} meters. ';

This is the tag template, which can be understood as the tag Function + template string, which is a new syntax specification.

Next, let's continue to look at the three parameters of the function. From the printed results of the code, we can see the corresponding results after they are run. The value of arr is an array: ["his name ",", height "," meters. "], And v1 is the variable name value:" Zhang San ", v2 is the variable height value: 1.8.

Do you see the rule? The first parameter, arr, is of the array type. Its content is other characters except $ {} in the template string, which forms the array Content in order, so the value of arr is ["His name is", ", height", "meters. "]; The second and second parameters are the values of the variable name and height corresponding to the order in the template string.

The tag template is a new syntax introduced by ES6. It is often used to filter users' illegal input and multi-language conversion. Because once we have mastered the usage of the tag template, we can take advantage of this feature and implement various functions as needed.

ES6 New String Function

Repeat () function: repeats the target string N times and returns a new string without affecting the target string.

Var name1 = "Wang hanyan"; // The target string var name2 = name1.repeat (3); // The variable name1 is repeated three times; console. log (name1); // result: Wang hanyan console. log (name2); // result: Wang hanyan

Des () function: determines whether a string contains a specified substring. If the return value is true, both inclusive and false indicate that the string does not contain the specified substring. The second parameter is optional, indicating the start position of the search.

Var name = "Wang hanyan"; // target string name. includes ('any'); // true, containing name. includes ('web'); // false, excluding name. des ('King', 1); // false, which starts from 2nd characters and does not contain

Traditionally, we can use the indexOf () function to implement this function. If a specified string is contained, the indexOf () function returns-1 if the substring is located for the first time. We can determine whether the string contains the specified substring by checking whether the returned value is-1. However, we can use the des () function instead of the indexOf () function, because its return value is more intuitive (true or false), we do not care about the position where the substring appears.

StartsWith (): determines whether the specified substring is at the beginning of the target string. The second parameter is optional, indicating the start position of the search.

Var name = "Wang hanyan"; // target string name. startsWith ('King'); // true, which appears at the beginning of name. startsWith ('hang'); // false, not at the beginning of name. startsWith ('hang', 1); // true, starting from 2nd characters

EndsWith () function: determines whether the substring is located at the end of the target string. The second parameter is optional, indicating that the substring contains the first N characters.

Var name = "I am Wang hanyan"; // target string name. endsWith ('my'); // false, not at the tail position name. endsWith ('any'); // true, name at the end. endsWith ('any', 5); // false, only for the first five characters name. endsWith ('any', 6); // true, for the first 6 Characters

In javascript, a character is fixed to 2 bytes. For characters that require 4 bytes to be stored, javascript considers it to be two characters, and its length is 2 at this time. For example, the character "bytes" is a character that requires 4 bytes of storage and the length is 2. What is the problem? Javascript cannot correctly read 4-byte characters. Let's try.

Var str1 = "front-end"; var str2 = "strong"; str1.length; // The length is 2str2. length; // The length is 2str1. charAt (0); // str1.charAt (1); // end str2.charAt (0); // 'str2. charAt (1'

We can see that the length of str1 and str2 are both 2, because the character "character" is a 4-byte character, and the character at the specified position can be returned using the charAt function (charAt) the str1 character string can be correctly read, but the four-byte characters cannot be correctly read. At this time, garbled characters are returned.

However, if we use the codePointAt () function provided by ES6, we can process the four-byte characters. Let's see how to use it.

Var str = "success"; str. codePointAt (); // result: 134071

The codePointAt () method correctly identifies a length of 2 Characters: "bytes, in addition, it can return the decimal number of the Code point correctly: 134071. The hexadecimal value of this number is 20bb7, and the corresponding Unicode code is \ u20bb7.

String. fromCodePoint () function: the function parameter is a character's corresponding code point, and the returned result is the corresponding character, even if the character is a 4-byte character, it can be correctly implemented.

We can use the 10-digit 134071 obtained above to reverse push.

String. fromCodePoint (134071); // Result: "success"
String. raw () function. It indicates that the function name raw is not processed. Just like this function, it returns the original appearance of the string, even if the string contains an escape character, it ignores it, direct output.

Console. log ('Hello \ nworld'); // output: helloworld console. log (String. raw 'Hello \ nwolrd '); // output: hello \ nwolrd

Summary:ES6 brings many practical extensions to the String: Template String, tag template, repeat function, des function, startsWith function, endsWith function, codePointAt function, String. fromCodePoint function, String. raw function.

The above es6 String extension (instance description) is all the content shared by Alibaba Cloud xiaobian. I hope you can give us a reference and support the help house.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.