JavaScript 中反引号 (`) 的用法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27678052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:30:31  来源:igfitidea点击:

Usage of the backtick character (`) in JavaScript

javascriptbacktickssingle-quotestemplate-stringsbackquote

提问by vancewang

In JavaScript, a backtickseems to work the same as a single quote. For instance, I can use a backtick to define a string like this:

在 JavaScript 中,反引号似乎与单引号的作用相同。例如,我可以使用反引号来定义这样的字符串:

var s = `abc`;

Is there a way in which the behavior of the backtick actually differs from that of a single quote?

反引号的行为实际上与单引号的行为不同吗?



† Note that among programmers, "backtick" is one name for what is more generally called the grave accent. Programmers also sometimes use the alternate names"backquote" and "backgrave". Also, on Stack Overflowand elsewhere, other common spellings for "backtick" are "back-tick" and "back tick".

† 请注意,在程序员中,“反引号”是更普遍称为重音符号的名称之一。程序员有时也使用备用名称“反引号”和“背刻”。此外,在 Stack Overflow和其他地方,“反引号”的其他常见拼写是“反引号”和“反引号”。

回答by try-catch-finally

This is a feature called template literals.

这是一个称为模板文字的功能。

They were called "template strings" in prior editions of the ECMAScript 2015 specification.

在 ECMAScript 2015 规范的早期版本中,它们被称为“模板字符串”。

Template literals are supported by Firefox 34, Chrome 41, and Edge 12 and above, but not by Internet Explorer.

Firefox 34、Chrome 41 和 Edge 12 及更高版本支持模板文字,但 Internet Explorer 不支持。

Template literals can be used to represent multi-line strings and may use "interpolation" to insert variables:

模板文字可用于表示多行字符串,并可使用“插值”来插入变量:

var a = 123, str = `---
   a is: ${a}
---`;
console.log(str);

Output:

输出:

---
   a is: 123
---

What is more important, they can contain not just a variable name, but any JavaScript expression:

更重要的是,它们不仅可以包含变量名,还可以包含任何 JavaScript 表达式:

var a = 3, b = 3.1415;

console.log(`PI is nearly ${Math.max(a, b)}`);

回答by Thalaivar

ECMAScript 6 comes up with a new type of string literal, using the backtick as the delimiter. These literals do allow basic string interpolation expressions to be embedded, which are then automatically parsed and evaluated.

ECMAScript 6 提出了一种新类型的字符串文字,使用反引号作为分隔符。这些文字确实允许嵌入基本的字符串插值表达式,然后自动解析和评估。

let person = {name: 'RajiniKanth', age: 68, greeting: 'Thalaivaaaa!' };

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);

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 literal, including function calls, inline function expression calls, and even other interpolated 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 whovariable with the "s"string, as opposed to 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:

在此,内部`${who}s`合并时插字符串字面量是一点点更好的方便了我们who的变量与"s"字符串,而不是who + "s"。另外要注意的是,内插字符串文字只是在它出现的地方进行词法作用域,而不是以任何方式动态作用域:

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 使用模板文字肯定更具可读性。

The plain old way:

简单的老方法:

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

With ECMAScript 6:

使用 ECMAScript 6:

`<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.

我们还可以标记模板字符串,当标记模板字符串时,文字和替换将传递给返回结果值的函数。

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. 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,虽然你当然可以留下他们作为以下参数就像我们上面那样的字符串(个人命名的参数value1value2等等)。

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. 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. Let's look at an example of creating reusable templates.

收集到我们的 values 数组中的参数是在字符串文字中找到的已经评估的插值表达式的结果。标记的字符串文字就像是在计算插值之后但在编译最终字符串值之前的处理步骤,让您可以更好地控制从文字生成字符串。让我们看一个创建可重用模板的示例。

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. 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 .rawproperty, 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 \nsequence, while the processed version of the string treats it like an unescaped real new-line. ECMAScript 6 comes with a built-in function that can be used as a string literal tag: String.raw(..). It simply passes through the raw versions of the strings:

如您所见,字符串的原始版本保留了转义\n序列,而字符串的处理版本将其视为未转义的真正换行符。ECMAScript 6 带有一个内置函数,可以用作字符串文字标签:String.raw(..). 它只是通过字符串的原始版本:

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

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

回答by Rohit Jindal

Backticks (`) are used to define template literals. Template literals are a new feature in ECMAScript 6 to make working with strings easier.

反引号 ( `) 用于定义模板文字。模板字面量是 ECMAScript 6 中的一项新功能,可以更轻松地处理字符串。

Features:

特征:

  • we can interpolate any kind of expression in the template literals.
  • They can be multi-line.
  • 我们可以在模板文字中插入任何类型的表达式。
  • 它们可以是多行的。

Note:we can easily use single quotes (') and double quotes (") inside the backticks (`).

注意:我们可以轻松地在反'引号 ( ") 内使用单引号 ( ) 和双引号 ( `)。

Example:

例子:

var nameStr = `I'm "Rohit" Jindal`;

To interpolate the variables or expression we can use the ${expression}notation for that.

为了插入变量或表达式,我们可以使用${expression}符号。

var name = 'Rohit Jindal';
var text = `My name is ${name}`;
console.log(text); // My name is Rohit Jindal

Multi-line strings means that you no longer have to use \nfor new lines anymore.

多行字符串意味着您不再需要使用\n新行。

Example:

例子:

const name = 'Rohit';
console.log(`Hello ${name}!
How are you?`);

Output:

输出:

Hello Rohit!
How are you?

回答by mrmaclean89

Backticks enclose template literals, previously known as template strings. Template literals are string literals that allow embedded expressions and string interpolation features.

反引号包含模板文字,以前称为模板字符串。模板文字是允许嵌入表达式和字符串插值功能的字符串文字。

Template literals have expressions embedded in placeholders, denoted by the dollar sign and curly brackets around an expression, i.e. ${expression}. The placeholder / expressions get passed to a function. The default function just concatenates the string.

模板文字在占位符中嵌入了表达式,由美元符号和表达式周围的大括号表示,即${expression}. 占位符/表达式被传递给一个函数。默认函数只是连接字符串。

To escape a backtick, put a backslash before it:

要转义反引号,请在它前面放一个反斜杠:

`\`` === '`'; => true

Use backticks to more easily write multi-line string:

使用反引号可以更轻松地编写多行字符串:

console.log(`string text line 1
string text line 2`);

or

或者

console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);

vs. vanilla JavaScript:

与普通 JavaScript 对比:

console.log('string text line 1\n' +
'string text line 2');

or

或者

console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');

Escape sequences:

转义序列:

  • Unicode escapes started by \u, for example \u00A9
  • Unicode code point escapes indicated by \u{}, for example \u{2F804}
  • Hexadecimal escapes started by \x, for example \xA9
  • Octal literal escapes started by \and (a) digit(s), for example \251
  • \u例如,由 开始的 Unicode 转义\u00A9
  • \u{}例如,由 指示的 Unicode 代码点转义\u{2F804}
  • \x例如,由 开始的十六进制转义\xA9
  • \和 (a) 数字开头的八进制文字转义,例如\251

回答by Willem van der Veen

Summary:

概括:

Backticks in JavaScript is a feature which is introduced in ECMAScript 6 // ECMAScript 2015 for making easy dynamic strings. This ECMAScript 6 feature is also named template string literal. It offers the following advantages when compared to normal strings:

JavaScript 中的反引号是 ECMAScript 6 // ECMAScript 2015 中引入的一项功能,用于制作简单的动态字符串。这个 ECMAScript 6 特性也被命名为模板字符串文字。与普通字符串相比,它具有以下优点:

  • In Template strings linebreaks are allowed and thus can be multiline. Normal string literals (declared with ''or "") are not allowed to have linebreaks.
  • We can easily interpolate variable values to the string with the ${myVariable}syntax.
  • 在模板字符串中允许换行,因此可以是多行的。普通字符串文字(用''或声明"")不允许有换行符。
  • 我们可以使用${myVariable}语法轻松地将变量值插入到字符串中。

Example:

例子:

const name = 'Willem';
const age = 26;

const story = `
  My name is: ${name}
  And I'm: ${age} years old
`;

console.log(story);

Browser compatibility:

浏览器兼容性:

Template string literal are natively supported by all major browser vendors (except Internet Explorer). So it is pretty save to use in your production code. A more detailed list of the browser compatibilities can be found here.

所有主要浏览器供应商(Internet Explorer 除外)本机都支持模板字符串文字。因此,在您的生产代码中使用它非常省钱。可以在此处找到浏览器兼容性的更详细列表。

回答by Ankit Kumar

Apart from string interpolation, you can also call a function using back-tick.

除了字符串插值,您还可以使用反引号调用函数。


var sayHello = function () {
    console.log('Hello', arguments);
}

// To call this function using ``

sayHello`some args`; // Check console for the output

// Or
sayHello`
    some args
`;

Check styled component. They use it heavily.

检查样式组件。他们大量使用它。

回答by NVRM

The good part is we can make basic maths directly:

好的部分是我们可以直接进行基本数学运算:

let nuts = 7

more.innerHTML = `

<h2>You collected ${nuts} nuts so far!

<hr>

Double it, get ${nuts + nuts} nuts!!

`
<div id="more"></div>

It became really useful in a factory function:

它在工厂函数中变得非常有用:

function nuts(it){
  return `
    You have ${it} nuts! <br>
    Cosinus of your nuts: ${Math.cos(it)} <br>
    Triple nuts: ${3 * it} <br>
    Your nuts encoded in BASE64:<br> ${btoa(it)}
  `
}

nut.oninput = (function(){
  out.innerHTML = nuts(nut.value)
})
<h3>NUTS CALCULATOR
<input type="number" id="nut">

<div id="out"></div>