ES6 template literals vs. concatenated strings(ES6 模板文字与串联字符串)
问题描述
I have the following code for ECMAScript 6 template literals:
let person = {name: 'John Smith'};
let tpl = `My name is ${person.name}.`;
let MyVar = "My name is " + person.name + ".";
console.log("template literal= " + tpl);
console.log("my variable = " + MyVar);
The output is as follows:
template literal= My name is John Smith.
my variable = My name is John Smith.
This is the fiddle.
I tried searching for the exact difference, but I couldn't find it, What is the difference between the following two statements?
let tpl = `My name is ${person.name}.`;
And
let MyVar = "My name is "+ person.name+".";
I am already able to get the string MyVar
concatenated with person.name
here, so what would be the scenario to use the template literal in?
If you are using template literals only with placeholders (e.g. `Hello ${person.name}`
) like in the question's example, then the result is the same as just concatenating strings. Subjectively it looks better and is easier to read, especially for multi-line strings or strings containing both '
and "
since you don't have to escape those characters any more.
Readability is a great feature, but the most interesting thing about templates are Tagged template literals:
let person = {name: 'John Smith'};
let tag = (strArr, name) => strArr[0] + name.toUpperCase() + strArr[1];
tag `My name is ${person.name}!` // Output: My name is JOHN SMITH!
In the third line of this example, a function named tag
is called. The content of the template string is split into multiple variables, that you can access in the arguments of the tag
function: literal sections (in this example the value of strArr[0]
is My name is
and the value of strArr[1]
is !
) and substitutions (John Smith
). The template literal will be evaluated to whatever the tag
function returns.
The ECMAScript wiki lists some possible use cases, like automatically escaping or encoding input, or localization. You could create a tag function named msg
that looks up the literal parts like My name is
and substitutes them with translations into the current locale's language, for example into German:
console.log(msg`My name is ${person.name}.`) // Output: Mein Name ist John Smith.
The value returned by the tag function doesn't even have to be a string. You could create a tag function named $
which evaluates the string and uses it as a query selector to return a collection of DOM nodes, like in this example:
$`a.${className}[href=~'//${domain}/']`
这篇关于ES6 模板文字与串联字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ES6 模板文字与串联字符串


- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01