ES6: template string

Time:2022-8-2

preface

Traditional string template
In traditional JavaScript, if we operate on DOM, string templates usually use the plus sign (+) to splice strings.

ES6 template string
Inverted quotation marks (`) represent ordinary strings, or multi line strings (arbitrary line breaks), and variables can be inserted (instead of the traditional plus sign splicing).

brief introduction

The template string uses inverted quotation marks (“) instead of double quotation marks and single quotation marks in the ordinary string.
Template strings can contain placeholders for specific syntax (${expression}). The expression in the placeholder and the surrounding text will be passed to a default function, which is responsible for connecting all parts.

If a template string starts with an expression, the string is called a tagged template string. The expression is usually a function that will be called after the template string is processed. You can manipulate the template string through this function before outputting the final result. When you use a backquote (`) in a template string, you need to precede it with an escape character (\).

Note: line breaks and spaces in the template string will be preserved, and if the variables in the template string are not declared, an error will be reported.

Later, all our examples are demonstrated by comparing traditional strings.

Basic Usage

//Traditional string splicing
Var STR1 = "I am:";
Var STR2 = "student";
window. Alert (STR1 + "one" + STR2)// I am: a student

//ES6 template string splicing
Var STR1 = "I am:";
Var STR2 = "student";
Window.alert (`${str1} one ${str2}`)// I am: a student

As you can see, template string splicing is more concise and intuitive.

You can also easily get multi line strings:

//Traditional writing
Var STR1 = "I am:";
Var STR2 = "student";
console.log(str1+'\n'+str2);
/*
I am:
student
*/

//ES6 template string writing
Var STR1 = "I am:";
Var STR2 = "student";
console.log(`${str1}
${str2}`);
/*
I am:
student
*/

Any character inserted in a new line is part of the template string.

If there is a string inside the brace, it will be output as is:

console.log(`hello ${'ES6'} !`)
// hello ES6 !

Insert expression

Embedding expressions (arbitrary expressions or object attributes, etc.) in ordinary strings makes the traditional methods slightly cumbersome and the string template more elegant.

//Traditional writing
var n1 = 10;
var n2 = 20;
console.log("n1+n2="+(n1+n2));//n1+n2=30

//ES6 template string writing
var n1 = 10;
var n2 = 20;
console.log(`n1+n2=${n1+n2}`);//n1+n2=30

It can be seen that it is not only hierarchical, but also intuitive.

Template string nesting

Template strings can also be nested.

const data = `
    ·1·
`;
//     ·1·

If you need to reference the template string itself, execute it when necessary, and write it as a function:

let data = (str) => `____${str}`;
console.log(data('123'));
// ____123

Template string call function

Similarly, the template string supports calling functions, ${function name}.

//Define a function
function demo(){
    return `Hello ES6!`
}
//Call demo()
Window.alert ('I want to call demo(): ${demo()} ');
//I want to call demo ():hello ES6!

Tagged template string

A more advanced form of template string is a template string with a tag. Tags enable you to parse Template Strings with functions. The first parameter of the tag function contains an array of string values. The remaining parameters are related to the expression.
Finally, your function can return the processed string (or it can return something completely different). The name of the function used for the tag can be named any name.

To put it bluntly, it is to calculate and connect the interpolation through a default function, add a label (function) in front of the template string, and the function will be automatically called for operation processing before the string is output. Just like the filters in Vue, react and other frameworks are similar.

//Tag function (array, N1, N2)
//Array is an array of literal values of strings
//N1/n2: calculation result of an expression

//Variables
Var name = 'Xiao Li';
var age = 102;

//Label function
function new_fun(strings, n1,n2) {

  //Array (I don't understand the following figure)
  var str0 = strings[0]; //  I am
  var str1 = strings[1]; //  this year
  var n1 = `*`; // *
  var n2 = `|`;// |

  //Finally, you need to return (otherwise, an error is reported)
  Return str0 + N1 + STR1 + N2 + ` ~ ~ I'm the tail `// If the sequence changes, the output changes

}

//Call label function (new_fun)
var output = new_ Fun ` I am ${name} this year ${age} `;

//Output printing
console. log(output); //  I'm * this year ~ ~ I'm tail

Note: return will be returned in the end, otherwise an error will be reported.