preface

Template strings are one of the important new syntactic features in ES6. They can be used as regular strings, to define multi-line strings, or to embed variables in strings.

The following is an example.

// Plain string 'In JavaScript'\n''// Multi-line string' In JavaScript this is not legal. 'console.log(' string text line 1 string text line 2'); // Embed variables in stringslet name = "Bob", time = "today";
`Hello ${name}, how are you ${time}? `Copy the code

But template strings have not only the functionality shown above, but also an often overlooked feature — tag templates.

Alert '123' // equivalent to alert(123)Copy the code

It can be followed by the name of a function that will be called to process the template string.

This article will delve into the tag template to help you understand this interesting feature through examples.

The label template

A tag template is not really a template, but a special form of function call. The “label” refers to the function, and the template string immediately following it is its argument.

Since the tag template is a form of function call, will the output of the two console. logs in the title be the same?

console.log(`The ${1 + 2}`)
//  3

console.log`The ${1 + 2}` / / /"".""3]Copy the code

Obviously, the result is different. Although 1+2=3 is output in both ways, the output from the tag template is also an array with two empty strings.

Take a look at the following example.

let a = 5;
let b = 10;

tag`Hello ${ a + b } world ${ a * b }`; // same as tag(['Hello '.' world '.' '], 15, 50);
Copy the code

From this example, we can see that if there are variables in the template character, the strings before and after the variable will be split into separate strings. These strings will form an array as the first argument of the function, and the variables of the template character will in turn become the remaining arguments of the function.

Note that if the variable in the template character is preceded by no other string, it will also be split into separate empty strings and placed in the first array argument.

Instance methods

From the above, we have gradually introduced the functions of tag templates. The following example method will give you an example of how to use tag templates.

functionPrint(arrList,... itemList){let items=[...arrList,...itemList];
	for(let item of items){
		console.log(item)
	}
}

Print`helloThe ${1 + 2}world`

// hello
// world
// 3
Copy the code

conclusion

These are my thoughts on the function of tag templates. If you have any ideas, please leave a comment.

Finally, I wish you success in your work and a happy life.