This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money

1. Basic use

Let’s look at the traditional string concatenation template, as follows

let username="Administrator";
let age=18;
let phone=123456789;
$('#addList').append(
  '<li>'+username+'<li>'+
  '<li>'+age+'<li>'+
  '<li>'+phone+'<li>'+)Copy the code

As you can see, this is quite cumbersome and can make reading difficult in the case of complex templates. To address this type of problem, template strings (backquotes) were introduced in ES6. Write the following

let username="Administrator";
let age=18;
let phone=123456789;
$('#addList').append(`
  <li>${username}</li>
  <li>${age}</li>
  <li>${phone}</li>
`)
Copy the code

You can see that not only can you define multi-line strings directly, but you can also embed variables directly in strings.

2. Embed variables

To embed a variable in a template string, you simply write the name of the variable in ${}. This does not only provide simple embedding variables, but also allows you to place any javaScript expression, string, number, etc. inside curly braces. Let’s look directly at the following code

let obj={
    numOne:1.numTwo:2.nameOne:"Brother".nameTwo:"Flower".ai:"Love",}function fn(name){
  return `${name}In? `
}

// Object reference
let a = `${obj.nameOne}In? `
alert(a);

// Numeric operations
let b = `${obj.numOne + obj.numTwo}`
alert(` 1 + 2 =${b}`)

// String concatenation one
let c = `${obj.nameOne + obj.ai + obj.nameTwo}`
alert(c)

// String concatenation two (concatenate string and number)
let c = `${obj.nameOne + obj.ai + obj.nameTwo + 'My brother doesn't love me anymore? ' + '123456789'}`
alert(c)

// Function call
let d = `${fn(obj.nameOne)}`
alert(d)

// The template string is nested, which returns the array contained in the p tag, separated by Spaces
let e = `<div>
The ${Object.keys(obj).map(item=>{
       return `<p>${obj[item]}</p>`
    }).join(' ')       //Output: < p >1</p> <p>2</P > <p> Brother </p> 

Floret </

P > <p> Love </p>}
</div>`
console.log(e) Copy the code

3. Label template

String templates can also be followed by a function and passed as arguments to the function body. If the template character contains variables, the template string and variables will be processed into multiple arguments before the function is called.

The first parameter is the cut string array, and each subsequent parameter is a variable. 2. The writing method is different from normal function parameter passing, as shown in the following code.

// It is possible to use value to accept the first and second arguments, but this is not practical, so using destruct syntax is best practice
//function test(stringArr, value1, value2){
function test(stringArr, ... values){
    console.log(stringArr)
    console.log(values)
}
let a = Content of the '1'
let b = Content of the '2'
// Execute the function
test`${a}---${b}` // Actual call form: test(['', '-- ', '], 'content 1',' content 2')
Copy the code

We can see the result of the above execution, first of allstringArrThere are three of them in the array, three dashes---Is a normally cut string, so where did the other two Spaces come from? Let’s continue our analysis and execute the following code

Let’s add strings at the beginning and end and see what happens

test'Test start${a}---${b}`  // Actual call form: test([' test start ', '-- ', '], 'content 1',' content 2')
test`${a}---${b}Test end '  // Actual call form: test(['', '-- ', 'end of test '],' content 1', 'content 2')
test'Test start${a}---${b}Test end '  / / actual call form: test ([' test 'in the beginning,' - ', 'test end],' 1 ', '2' content)
Copy the code

When the first function is executed, the first space in the array is already occupied by the “test start” string.

Execute the second function. The last space of the array is already occupied by the “test end” string.

In the third function, all the Spaces in the array are already occupied by the “test start” and “test end” strings.

Note: if the template string does not start or end with a string, the function will process arguments with Spaces instead

4. Application scenarios of label templates

Above we have learned how to use the tag template, also know the characteristics of the tag template, below we give an example 🌰

4.1 Filtering HTML Strings

To prevent users from entering malicious code, we can use the tag template to reformat the user input as follows:

// Get the contents of the input box
let sender = ''; 
// The concatenated content is displayed in the page
let appendHtml = '<p> What you typed is${sender}</p>`
$("body").append(appendHtml)
Copy the code

The alert function is executed after the code is executed on the console, and while it may not look very malicious, it can be used by someone with an ulterior motive to create truly malicious code.To prevent this from happening, we can define a function that escapes the tags in malicious code so that the code will not be executed.

//stringArr: an array cut from the original string
//values: array of variables
function SaferHTML(stringArr,... values) {
  let s = stringArr[0]
  for (let i = 0; i < values.length; i++) {
    let strValue = String(values[i]);
    s += strValue.replace(/&/g."&amp;")  // Escape &= => &
            .replace(/</g."&lt;")        // Escape < ==> <
            .replace(/>/g."&gt;");       // Escape > ==> >

    s += stringArr[i+1];
  }
  return s;
}
// Get the contents of the input box
let sender = ''; 
// The concatenated content is displayed in the page
let appendHtml = SaferHTML'<p> What you typed is${sender}</p>`
$("body").append(appendHtml)
Copy the code

After execution, insert a string at the bottom of the body as normal

Since the tag template function converts the string and variable to the corresponding parameter, we only need to process the parameter of the variable and return the normal concatenation.