Home > Web Front-end > JS Tutorial > ES6 template string example sharing

ES6 template string example sharing

小云云
Release: 2018-01-26 16:44:12
Original
1808 people have browsed it

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);// 一步
Copy after login

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>
Copy after login

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);
Copy after login

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.
Copy after login

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!
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template