Home Web Front-end JS Tutorial How to use ES6 template strings

How to use ES6 template strings

May 29, 2018 am 10:12 AM
use string stencil

This time I will show you how to use ES6 templatesStrings, what are the precautions when using ES6 template strings, the following is a practical case, let's take a look.

1. Previously we could also use JavaScript to output a template string, usually as follows:

$("#result").append(
    "He is <b>"+person.name+"</b>"+"and we wish to know his"+person.age+".That is all" 
    );
Copy after login

But we can see: Such a traditional approach requires the use A lot of "" (double quotes) and splicing can get the template we need. But this is very inconvenient.

So ES6 provides template strings, marked with ` (backtick), and variables enclosed with ${}. The above example can be written as follows using a template string:

$("#result").append(
  `He is <b>${person.name}</b>and we wish to know his${person.age}.that is all`
    );
Copy after login

This approach is much simpler, and we no longer need to use a large number 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 variable first, and then embed the variable in the template string:

var name="zzw";
` ${name},no matter what you do,
 I trust you.`
Copy after login

4. Obviously, since the backtick is the identifier of the template string, if we If we need to use backticks in the string, we need to escape them, as shown below:

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

The output result is as follows:

6. You can put any JavaScriptexpression## in the curly brackets in ${} #, you can also perform operations and reference object properties.

var x=88;
var y=100;
console.log(`x=${++x},y=${x+y}`);
Copy after login
The result is as follows:

#7. Even more powerful is: the template string can also call functions:

function string(){
  return "zzw likes es6!";
}
console.log(`你想说什么?嗯,${string()}`);
Copy after login
Result As shown below:

#In addition, if the result of the function is not a string, it will be converted into a string according to the general rules:

function string(){
    return 666;
  }
  console.log(`你想说什么? 嗯,${string()}`);
Copy after login
The result is as follows Shown:

Here, the number 666 is actually converted into the string 666.

8. If the variable in ${} If it is not named, an error will be reported:

console.log(`你想说什么? 嗯,${string()}`);
Copy after login
In the above code, the string() function is not declared, so an error will be reported:

9. In fact , we can also enter a string in ${}, and the knowledge result will still return a string:

console.log(`你想说什么?嗯,${"其实我不是变量~"}`);
Copy after login
The result is as follows:

10. If you want to quote 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"));
Copy after login
The result is as follows:

I believe you have mastered it after reading the case in this article Method, for more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to implement a custom multi-selection event for WeChat applet

How to create-react- The app is modified to support multiple pages

The above is the detailed content of How to use ES6 template strings. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

How to use Xiaomi Auto app How to use Xiaomi Auto app Apr 01, 2024 pm 09:19 PM

Xiaomi car software provides remote car control functions, allowing users to remotely control the vehicle through mobile phones or computers, such as opening and closing the vehicle's doors and windows, starting the engine, controlling the vehicle's air conditioner and audio, etc. The following is the use and content of this software, let's learn about it together . Comprehensive list of Xiaomi Auto app functions and usage methods 1. The Xiaomi Auto app was launched on the Apple AppStore on March 25, and can now be downloaded from the app store on Android phones; Car purchase: Learn about the core highlights and technical parameters of Xiaomi Auto, and make an appointment for a test drive. Configure and order your Xiaomi car, and support online processing of car pickup to-do items. 3. Community: Understand Xiaomi Auto brand information, exchange car experience, and share wonderful car life; 4. Car control: The mobile phone is the remote control, remote control, real-time security, easy

What is chirp down? -How to use chirp down What is chirp down? -How to use chirp down Mar 18, 2024 am 11:46 AM

Chirp Down can also be called JJDown. This is a video download tool specially created for Bilibili. However, many friends do not understand this software. Today, let the editor explain to you what Chirp Down is? How to use chirp down. 1. The origin of Chirpdown Chirpdown originated in 2014. It is a very old video downloading software. The interface adopts Win10 tile style, which is simple, beautiful and easy to operate. Chirna is the poster girl of Chirpdown, and the artist is あさひクロイ. Jijidown has always been committed to providing users with the best download experience, constantly updating and optimizing the software, solving various problems and bugs, and adding new functions and features. The function of Chirp Down Chirp Down is

How to determine whether a Golang string ends with a specified character How to determine whether a Golang string ends with a specified character Mar 12, 2024 pm 04:48 PM

Title: How to determine whether a string ends with a specific character in Golang. In the Go language, sometimes we need to determine whether a string ends with a specific character. This is very common when processing strings. This article will introduce how to use the Go language to implement this function, and provide code examples for your reference. First, let's take a look at how to determine whether a string ends with a specified character in Golang. The characters in a string in Golang can be obtained through indexing, and the length of the string can be

See all articles