Home >Web Front-end >Front-end Q&A >How to use backticks in es6

How to use backticks in es6

青灯夜游
青灯夜游Original
2022-03-07 18:21:492198browse

es6 Usage of backticks: 1. Define a single-line string; 2. Define a multi-line string. The spaces, indents and newlines in the string will be retained in the output; 3. In the string Embed variables in "${}", for example "`Hello ${name}`"

How to use backticks in es6

##The operating environment of this tutorial: windows7 System, ECMAScript version 6, Dell G3 computer.

Template string (template string) is an enhanced version of the string, identified by backtick (`). It can be used as an ordinary string, or it can be used to define multi-line strings, or to embed variables in strings.

// 字符串中嵌入变量
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`

If backticks need to be used in the template string, they must be escaped with backslashes.


 var greeting = `\`Yo\` World!`;

If you use a template string to represent a multi-line string, all spaces and indentations will be preserved in the output.

$('#list').html(`
<ul>
  <li>first</li>
  <li>second</li>
</ul>
`);

If you don't want this line break, you can use the trim method to eliminate it.

$(&#39;#list&#39;).html(`
<ul>
  <li>first</li>
  <li>second</li>
</ul>
`.trim());

To embed variables in the template string, the variable name needs to be written in

${}.

【Related recommendations:

javascript video tutorial, web front-end

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

Statement:
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