Recently, I have used ES6 template strings in my project, which are summarized here.
1. Previously we could also use JavaScript to output template strings, usually as follows:
$("#result").append( "He is <b>"+person.name+"</b>"+"and we wish to know his"+person.age+".That is all" );
But we can see that this traditional approach requires using a lot of "" (double quotes) and + to splice it together to get the template we need. But this is very inconvenient.
So ES6 provides template strings, which are marked with ` (backtick) and variables are enclosed with ${}. The above example can be written as follows using template strings:
$("#result").append( `He is <b>${person.name}</b>and we wish to know his${person.age}.that is all` );
This approach is much simpler. We no longer need to use a lot of "" and + to splice strings and variables.
2. Of course, variables can be introduced into the template string, and it is also possible not to use variables. As shown below:
` I am a man.`
` No matter what you do,
I trust you.`
3. We can also define the variables first and then embed the variables in the template string:
var name="zzw"; ` ${name},no matter what you do, I trust you.`
4. Obviously, since the backtick is the identifier of the template string, if we need to use the backtick in the string, we need to escape it, as follows:
`No matter` what you do,
I trust you.`
5. Note: If you use template strings to represent multi-line strings, all spaces and indents will be saved in the output! !
console.log( `No matter` what you do, I trust you.`);
The output is as follows:
6. You can put any JavaScript expression in the curly brackets in ${}, perform operations, and reference object properties.
var x=88; var y=100; console.log(`x=${++x},y=${x+y}`);
The result is as follows:
7. Even more powerful: the template string can also call functions:
function string(){ return "zzw likes es6!"; } console.log(`What do you want to say? Well, ${string()}`);
The result is as follows:
In addition, if the result of the function is not a string, it will be converted to a string according to the general rules:
function string(){ return 666; } console.log(`What do you want to say? Well, ${string()}`);
The result is as follows:
Here, the number 666 is actually converted into the string 666.
8. If the variable in ${} is not named, an error will be reported:
console.log(`What do you want to say? Well, ${string( )}`);
In the above code, the string() function is not declared, so an error is reported:
9. In fact, we can also enter a string in ${}, and the knowledge result will still return a string:
console.log(`What do you want to say? Well, ${"Actually, I am not a variable~"}`) ;
The result is as follows:
10. If you want to reference the template string itself, you can write it like this:
let str="return"+"`Hello! ${name}`"; let func=new Function("name",str); console.log(func("zzw"));
The results are as follows: