A new type of string literal syntax introduced in ES6 - template string. Technically explained, a template string is a string literal that embeds expressions within a string literal. To put it simply, it is a string with added variable function.
ES6 provides us with template strings, and the syntax uses backticks`. Template strings have the following three advantages:
Multi-line text
Inserting variables into the string
Insert expressions into strings
Basic syntax
The declaration of template strings is the same as that of ES5 strings.
// ES5 var name = 'xixi'; console.log(name);// xixi // ES6 let name4ES6 = `一步`; console.log(name4ES6);// 一步
Multi-line text
In the era when Jquery was popular, we often spliced html fragments and then replaced nodes. Write a piece of ES5 code for everyone to experience:
var str = '<html>' + '<p>啦拉拉</p>' + '<p>xixixi</p>' + '</html>'; console.log(str);// <html><p>啦拉拉</p><p>xixixi</p></html>
ES6 supports multi-line text, and the above code is much easier to implement.
let str4ES6 = `<html> <p>啦拉拉</p> <p>xixixix</p> </html>`; console.log(str4ES6);
You can insert variables or expressions
// ES5 var name = 'xixi'; var age = 27; var info = 'my name is ' + name + ' , age is ' + age + '.'; console.log(info);// my name is xixi , age is 27.
ES6’s template string is much easier to implement. The key syntax is ${}, in which any js expression can be inserted.
let name = 'xixi'; let age = 27; let info = `my name is ${name}, my age is ${age}. just a test ${1 + 10}!`; console.log(info);// my name is xixi, my age is 27. just a test 11!
Summary
ES6 template string is so simple and easy to use.
Related recommendations:
Detailed explanation of mutual conversion between JS numbers and strings
A collection of commonly used JS interception string methods
jquery method of splicing ajax json and string
The above is the detailed content of ES6 template string example sharing. For more information, please follow other related articles on the PHP Chinese website!