简体   繁体   English

ES6 模板文字与连接字符串

[英]ES6 Template Literals Vs concatenated strings

I have the following code for Ecma-Script-6 template literals我有以下 Ecma-Script-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 couldn't find it, My question is what is the difference between these 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 ?我已经能够在这里将字符串MyVarperson.name连接起来,那么使用模板文字的场景是什么?

If you are using template literals only with placeholders (eg `Hello ${person.name}` ) like in the question's example, then the result is the same as just concatenating strings.如果您在问题示例中仅使用带有占位符(例如`Hello ${person.name}` )的模板文字,则结果与仅连接字符串相同。 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.在此示例的第三行中,调用了名为tag的函数。 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 ).模板字符串的内容被拆分为多个变量,您可以在tag函数的参数中访问这些变量:文字部分(在本例中, strArr[0]的值是My name is ,而strArr[1]的值是! )和换人( John Smith )。 The template literal will be evaluated to whatever the tag function returns.模板文字将被评估为tag函数返回的任何内容。

The ECMAScript wiki lists some possible use cases, like automatically escaping or encoding input, or localization. ECMAScript wiki列出了一些可能的用例,例如自动转义或编码输入,或本地化。 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:您可以创建一个名为msg的标记函数,它会查找诸如My name is类的文字部分,并将它们替换为当前区域设置语言的翻译,例如德语:

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 :您可以创建一个名为$的标记函数,它评估字符串并将其用作查询选择器来返回 DOM 节点的集合,如下例所示

$`a.${className}[href=~'//${domain}/']`

ES6 comes up with a new type of string literal, using the ` back-tick as the delimiter. ES6提出了一种新类型的字符串文字,使用`反引号作为分隔符。 These literals do allow basic string interpolation expressions to be embedded, which are then automatically parsed and evaluated.这些文字确实允许嵌入基本的字符串插值表达式,然后自动解析和评估。

let actor = {name: 'RajiniKanth', age: 68};

let oldWayStr = "<p>My name is " + actor.name + ",</p>\n" +
  "<p>I am " + actor.age + " old</p>\n";

let newWayHtmlStr =
 `<p>My name is ${actor.name},</p>
  <p>I am ${actor.age} old</p>`;

console.log(oldWayStr);
console.log(newWayHtmlStr);

As you can see, we used the ..`` around a series of characters, which are interpreted as a string literal, but any expressions of the form ${..} are parsed and evaluated inline immediately.如您所见,我们在一系列字符周围使用了 ..``,这些字符被解释为字符串字面量,但任何${..}形式的表达式都会被立即内联解析和评估。

One really nice benefit of interpolated string literals is they are allowed to split across multiple lines:内插字符串文字的一个非常好的好处是允许它们跨多行拆分:

var Actor = {"name" : "RajiniKanth"};

var text =
`Now is the time for all good men like ${Actor.name}
to come to the aid of their
country!`;
console.log( text );
// Now is the time for all good men
// to come to the aid of their
// country!

Interpolated Expressions内插表达式

Any valid expression is allowed to appear inside ${..} in an interpolated string lit‐ eral , including function calls, inline function expression calls, and even other interpo‐ lated string literals !任何有效的表达式都可以出现在${..}中的内插字符串lit‐ eral ,包括函数调用、内联函数表达式调用,甚至其他内interpo‐ lated string literals

function upper(s) {
 return s.toUpperCase();
}
var who = "reader"
var text =
`A very ${upper( "warm" )} welcome
to all of you ${upper( `${who}s` )}!`;
console.log( text );
// A very WARM welcome
// to all of you READERS!

Here, the inner ${who}s`` interpolated string literal was a little bit nicer convenience for us when combining the who variable with the "s" string, as opposed to who + "s".在这里,当将 who 变量与"s"字符串结合时,内部 ${who}s`` 内插字符串文字对我们来说更加方便,而不是 who + "s"。 Also to keep an note is an interpolated string literal is just lexically scoped where it appears, not dynamically scoped in any way另外要注意的是,内插字符串文字只是在它出现的地方在lexically scoped ,而不是以任何方式dynamically scoped

function foo(str) {
 var name = "foo";
 console.log( str );
}
function bar() {
 var name = "bar";
 foo( `Hello from ${name}!` );
}
var name = "global";
bar(); // "Hello from bar!"

Using the template literal for the HTML is definitely more readable by reducing the annoyance.通过减少烦恼,为 HTML 使用template literal肯定更具可读性。

The plain old way:简单的老方法:

'<div class="' + className + '">' +
  '<p>' + content + '</p>' +
  '<a href="' + link + '">Let\'s go</a>'
'</div>';

With ES6 :使用ES6

`<div class="${className}">
  <p>${content}</p>
  <a href="${link}">Let's go</a>
</div>`
  • Your string can span multiple lines.您的字符串可以跨越多行。
  • You don't have to escape quotation characters.您不必转义引号字符。
  • You can avoid groupings like: '">'您可以避免分组,如:“>”
  • You don't have to use the plus operator.您不必使用加号运算符。

Tagged Template Literals标记模板文字

We can also tag a template string, when a template string is tagged, the literals and substitutions are passed to function which returns the resulting value.我们还可以标记一个template字符串,当一个template字符串标记,在literals和替换传递给函数返回的结果值。

function myTaggedLiteral(strings) {
  console.log(strings);
}

myTaggedLiteral`test`; //["test"]

function myTaggedLiteral(strings,value,value2) {
  console.log(strings,value, value2);
}
let someText = 'Neat';
myTaggedLiteral`test ${someText} ${2 + 3}`;
// ["test ", " ", ""]
// "Neat"
// 5

We can use the spread operator here to pass multiple values.我们可以在这里使用spread运算符来传递多个值。 The first argument — we called it strings — is an array of all the plain strings (the stuff between any interpolated expressions).第一个参数——我们称之为字符串——是一个包含所有普通字符串(任何内插表达式之间的内容)的数组。

we then gather up all subsequent arguments into an array called values using the ... gather/rest operator , though you could of course have left them as individual named parameters following the strings parameter like we did above (value1, value2 etc) .然后,我们使用... gather/rest operator将所有后续参数收集到一个名为 values 的数组中,尽管您当然可以像我们上面所做的那样将它们作为单独的命名参数保留在字符串参数之后(value1, value2 etc)

function myTaggedLiteral(strings,...values) {
  console.log(strings);
  console.log(values);    
}

let someText = 'Neat';
myTaggedLiteral`test ${someText} ${2 + 3}`;
// ["test ", " ", ""]
// ["Neat", 5]

The argument(s) gathered into our values array are the results of the already evaluated interpolation expressions found in the string literal.收集到我们的 values 数组中的argument(s)是在字符串文字中找到的已经评估的插值表达式的结果。 A tagged string literal is like a processing step after the interpolations are evaluated but before the final string value is compiled, allowing you more control over generating the string from the literal. tagged string literal就像是在计算插值之后但在编译最终字符串值之前的处理步骤,让您可以更好地控制从文字生成字符串。 Let's look at an example of creating a re-usable templates .让我们看一个创建可re-usable templates的示例。

const Actor = {
  name: "RajiniKanth",
  store: "Landmark"
}

const ActorTemplate = templater`<article>
  <h3>${'name'} is a Actor</h3>
  <p>You can find his movies at ${'store'}.</p>

</article>`;

function templater(strings, ...keys) {
  return function(data) {
  let temp = strings.slice();
  keys.forEach((key, i) => {
  temp[i] = temp[i] + data[key];
  });
  return temp.join('');
  }
};

const myTemplate = ActorTemplate(Actor);
console.log(myTemplate);

Raw Strings原始字符串

our tag functions receive a first argument we called strings , which is an array .我们的标签函数接收我们称为strings的第一个参数,它是一个array But there's an additional bit of data included: the raw unprocessed versions of all the strings.但是还包括一些额外的数据:所有字符串的原始未处理版本。 You can access those raw string values using the .raw property, like this:您可以使用.raw属性访问这些原始字符串值,如下所示:

function showraw(strings, ...values) {
 console.log( strings );
 console.log( strings.raw );
}
showraw`Hello\nWorld`;

As you can see, the raw version of the string preserves the escaped \\n sequence, while the processed version of the string treats it like an unescaped real new-line.如您所见,字符串的raw版本保留了转义的 \\n 序列,而字符串的处理版本将其视为未转义的真正换行符。 ES6 comes with a built-in function that can be used as a string literal tag: String.raw(..) . ES6带有一个内置函数,可以用作字符串文字标签: String.raw(..) It simply passes through the raw versions of the strings :它只是通过strings的原始版本:

console.log( `Hello\nWorld` );
/* "Hello
World" */

console.log( String.raw`Hello\nWorld` );
// "Hello\nWorld"

It's a lot cleaner and as stated in the comments, is a common features in another languages.正如评论中所述,它更清晰,是其他语言的共同特征。 The other thing that I found nice was the line breaks, very useful when writing strings.我发现的另一件事是换行符,在编写字符串时非常有用。

let person = {name: 'John Smith', age: 24, greeting: 'Cool!' };

let usualHtmlStr = "<p>My name is " + person.name + ",</p>\n" +
                   "<p>I am " + person.age + " old</p>\n" +
                   "<strong>\"" + person.greeting +"\" is what I usually say</strong>";


let newHtmlStr = 
 `<p>My name is ${person.name},</p>
  <p>I am ${person.age} old</p>
  <p>"${person.greeting}" is what I usually say</strong>`;


console.log(usualHtmlStr);
console.log(newHtmlStr);

While, my answer does not directly address the question.虽然,我的回答并没有直接解决这个问题。 I thought it may be of some interest to point out one drawback of using template literals in favor of array join.我认为指出使用模板文字代替数组连接的一个缺点可能会引起一些兴趣。

Lets say I have可以说我有

let patient1 = {firstName: "John", lastName: "Smith"};
let patient2 = {firstName: "Dwayne", lastName: "Johnson", middleName: "'The Rock'"};

So some patients have a middleName and others do not.所以有些患者有一个中间名,而另一些则没有。

If I wanted a string representing the full name of a patient如果我想要一个代表患者全名的字符串

let patientName = `${patient1.firstName} ${patient1.middleName} ${patient1.lastName}`;

Then this would become "John undefined Smith"然后这将成为“John undefined Smith”

However if I did但是,如果我这样做了

let patientName = [patient1.firstName, patient1.middleName,  patient1.lastName].join(" ");

Then this would become just "John Smith"然后这将变成只是“约翰史密斯”

EDIT编辑

General_Twyckenham pointed out that a join on " " would result in an extra space between "John" and "Smith". General_Twyckenham 指出“”上的连接会导致“John”和“Smith”之间出现额外的空格。

To get around this you can have a filter before the join to get rid of falsy values: [patient1.firstName, patient1.middleName, patient1.lastName].filter(el => el).join(" ");为了解决这个问题,您可以在加入之前使用过滤器来去除虚假值: [patient1.firstName, patient1.middleName, patient1.lastName].filter(el => el).join(" ");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM