Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Template string literal

The template string is enclosed by two backquotes. Writing inside ‘ ‘breaks the single-line format of the string. Using backquotes to enclose the core allows us to write multiple lines, such as + concatenation, which can be more obvious in code writing

In the original to write a newline string, you can use () to enlarge, internal use newline character \n for newline, not very convenient to write, also not convenient to read…

Here’s a comparison:

let old_str = (
  'This is the first line, the next line needs to be wrapped with a newline character.'
  + '\n That's the second line,'
  + '\n the newline character is in Chinese on the second line, but if the following line is in English, let's see,'
  + '\nhow can you see this line? '
  + '\nhow can you see this line? '
  + What is nhow above '\n, and is it easy to confuse? '
);

let new_str = 'This is the beginning of the first line, and the next line needs to be wrapped with a newline character. This is the second line, and the newline character is a little bit more obvious on the second line. If the next line is in English, let's see, how can you see this line? how can you see this line? What is nhow above, is it easy to confuse? `

old_str  === new_str // ---> true

Copy the code

A placeholderThe ${}

In the string template, we can use variables instead of defined values; The original use of double quotes concatenation is too troublesome! .

const NAME = 'iwin621'
const AGE = 21

let my_name_old_style = "My name is." + NAME + "This is my year."+ AGE + "Old"

let my_name_new_style = 'My name is${NAME}This year, I${AGE}At the age of `

Copy the code

The above template string shorthand, much easier

The cost of risk

Doesn’t the string template look better with two back quotes? But the back quotation mark is in the upper left corner of the keyboard, so it is easy to press the wrong one. For example, I often press the numeric key 1. There is also the potential for handwriting errors, which increases the risk cost.

In addition, such templates provide a breeding ground for more malicious scripts because they are inherently capable of parsing internal code snippets, such as writing a