javascript 模板

The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

作者选择了COVID-19救济基金来接受捐赠,这是Write for DOnations计划的一部分。

介绍 (Introduction)

The 2015 edition of the ECMAScript specification (ES6) added template literals to the JavaScript language. Template literals are a new form of making strings in JavaScript that add a lot of powerful new capabilities, such as creating multi-line strings more easily and using placeholders to embed expressions in a string. In addition, an advanced feature called tagged template literals allows you to perform operations on the expressions within a string. All of these capabilities increase your options for string manipulation as a developer, letting you generate dynamic strings that could be used for URLs or functions that customize HTML elements.

2015年版ECMAScript规范(ES6)向JavaScript语言添加了模板文字 。 模板文字是在JavaScript中制作字符串的一种新形式,它增加了许多强大的新功能,例如更轻松地创建多行字符串以及使用占位符将表达式嵌入字符串中。 此外,称为标记模板文字的高级功能使您可以对字符串中的表达式执行操作。 所有这些功能都增加了您作为开发人员进行字符串操作的选项,从而使您可以生成可用于URL或自定义HTML元素的函数的动态字符串。

In this article, you will go over the differences between single/double-quoted strings and template literals, running through the various ways to declare strings of different shape, including multi-line strings and dynamic strings that change depending on the value of a variable or expression. You will then learn about tagged templates and see some real-world examples of projects using them.

在本文中,您将遍历单引号/双引号字符串和模板文字之间的区别,通过各种方式声明不同形状的字符串,包括多行字符串和根据变量值而变化的动态字符串。或表达。 然后,您将了解带标签的模板,并看到一些使用它们的项目的真实示例。

声明字符串 (Declaring Strings)

This section will review how to declare strings with single quotes and double quotes, and will then show you how to do the same with template literals.

本节将回顾如何用单引号和双引号声明字符串,然后向您展示如何对模板文字进行相同的操作。

In JavaScript, a string can be written with single quotes (' '):

在JavaScript中,字符串可以用单引号( ' ' )编写:

const single = 'Every day is a good day when you paint.'

A string can also be written with double quotes (" "):

字符串也可以用双引号( " " )编写:

const double = "Be so very light. Be a gentle whisper."

There is no major difference in JavaScript between single- or double-quoted strings, unlike other languages that might allow interpolation in one type of string but not the other. In this context, interpolation refers to the evaluation of a placeholder as a dynamic part of a string.

在JavaScript中,单引号或双引号之间没有什么大的不同,不像其他语言可能允许在一种类型的字符串中插值 ,而另一种则不允许插值 。 在这种情况下,插值将占位符的评估称为字符串的动态部分。

The use of single- or double-quoted strings mostly comes down to personal preference and convention, but used in conjunction, each type of string only needs to escape its own type of quote:

单引号或双引号字符串的使用主要取决于个人喜好和约定,但是结合使用,每种类型的字符串仅需要转义其自己的引号类型:

// Escaping a single quote in a single-quoted string
const single = '"We don\'t make mistakes. We just have happy accidents." - Bob Ross'// Escaping a double quote in a double-quoted string
const double = "\"We don't make mistakes. We just have happy accidents.\" - Bob Ross"console.log(single);
console.log(double);

The result of the log() method here will print the same two strings to the console:

这里的log()方法的结果会将相同的两个字符串打印到控制台 :


Output
"We don't make mistakes. We just have happy accidents." - Bob Ross
"We don't make mistakes. We just have happy accidents." - Bob Ross

Template literals, on the other hand, are written by surrounding the string with the backtick character, or grave accent (`):

另一方面,模板文字是通过用反引号或重音符( ` )包围字符串来编写的:

const template = `Find freedom on this canvas.`

They do not need to escape single or double quotes:

他们不需要转义单引号或双引号:

const template = `"We don't make mistakes. We just have happy accidents." - Bob Ross`

However, they do still need to escape backticks:

但是,他们仍然需要避免反引号:

const template = `Template literals use the \` character.`

Template literals can do everything that regular strings can, so you could possibly replace all strings in your project with them and have the same functionality. However, the most common convention in codebases is to only use template literals when using the additional capabilities of template literals, and consistently using the single or double quotes for all other simple strings. Following this standard will make your code easier to read if examined by another developer.

模板文字可以完成常规字符串可以执行的所有操作,因此您可以用它们替换项目中的所有字符串,并且具有相同的功能。 但是,代码库中最常见的约定是仅在使用模板文字的附加功能时才使用模板文字,并对所有其他简单字符串始终使用单引号或双引号。 如果由另一位开发人员检查,遵循此标准将使您的代码更易于阅读。

Now that you’ve seen how to declare strings with single quotes, double quotes, and backticks, you can move on to the first advantage of template literals: writing multi-line strings.

既然您已经了解了如何使用单引号,双引号和反引号声明字符串,那么您可以继续使用模板文字的第一个优点:编写多行字符串。

多行字符串 (Multi-line Strings)

In this section, you will first run through the way strings with multiple lines were declared before ES6, then see how template literals make this easier.

在本节中,您将首先介绍在ES6之前声明多行字符串的方式,然后查看模板文字如何使之更容易。

Originally, if you wanted to write a string that spans multiple lines in your text editor, you would use the concatenation operator. However, this was not always a straight-forward process. The following string concatenation seemed to run over multiple lines:

最初,如果您想在文本编辑器中编写一个跨越多行的字符串,则可以使用串联运算符 。 但是,这并不总是简单的过程。 以下字符串连接似乎遍历了多行:

const address = 'Homer J. Simpson' + '742 Evergreen Terrace' + 'Springfield'

This might allow you to break up the string into smaller lines and include it over multiple lines in the text editor, but it has no effect on the output of the string. In this case, the strings will all be on one line and not separated by newlines or spaces. If you logged address to the console, you would get the following:

这可能使您可以将字符串分解为较小的行,并在文本编辑器中将其包含在多行中,但是它对字符串的输出没有影响。 在这种情况下,字符串将全部在一行上,并且不由换行符或空格分隔。 如果您将address登录到控制台,则会得到以下信息:


Output
Homer J. Simpson742 Evergreen TerraceSpringfield

You can use the backslash character (\) to continue the string onto multiple lines:

您可以使用反斜杠字符( \ )将字符串继续到多行:

const address ='Homer J. Simpson\742 Evergreen Terrace\Springfield'

This will retain any indentation as whitespace, but the string will still be on one line in the output:

这将保留所有缩进作为空格,但是字符串仍将在输出中位于一行:


Output
Homer J. Simpson  742 Evergreen Terrace  Springfield

Using the newline character (\n), you can create a true multi-line string:

使用换行符( \n ),您可以创建一个真正的多行字符串:

const address = 'Homer J. Simpson\n' + '742 Evergreen Terrace\n' + 'Springfield'

When logged to the console, this will display the following:

登录到控制台后,将显示以下内容:


Output
Homer J. Simpson
742 Evergreen Terrace
Springfield

Using newline characters to designate multi-line strings can be counterintuitive, however. In contrast, creating a multi-line string with template literals can be much more straight-forward. There is no need to concatenate, use newline characters, or use backslashes. Just pressing ENTER and writing the string across multiple lines works by default:

但是,使用换行符来指定多行字符串可能会违反直觉。 相反,使用模板文字创建多行字符串会更加简单明了。 无需连接,使用换行符或使用反斜杠。 默认情况下,只需按ENTER并跨多行写入字符串即可:

const address = `Homer J. Simpson
742 Evergreen Terrace
Springfield`

The output of logging this to the console is the same as the input:

将此日志记录到控制台的输出与输入相同:


Output
Homer J. Simpson
742 Evergreen Terrace
Springfield

Any indentation will be preserved, so it’s important not to indent any additional lines in the string if that is not desired. For example, consider the following:

任何缩进都将保留,因此,如果不需要,不要缩进字符串中的任何其他行,这一点很重要。 例如,考虑以下内容:

const address = `Homer J. Simpson742 Evergreen TerraceSpringfield`

Although this style of writing the line might make the code more human readable, the output will not be:

尽管这种写法可能会使代码更易于阅读,但输出不会是:


Output
Homer J. Simpson742 Evergreen TerraceSpringfield

With multi-line strings now covered, the next section will deal with how expressions are interpolated into their values with the different string declarations.

现在涵盖了多行字符串,下一节将介绍如何使用不同的字符串声明将表达式插入到它们的值中。

表达式插值 (Expression Interpolation)

In strings before ES6, concatenation was used to create a dynamic string with variables or expressions:

在ES6之前的字符串中,串联用于创建带有变量或表达式的动态字符串:

const method = 'concatenation'
const dynamicString = 'This string is using ' + method + '.'

When logged to the console, this will yield the following:

登录到控制台后,将产生以下结果:


Output
This string is using concatenation.

With template literals, an expression can be embedded in a placeholder. A placeholder is represented by ${}, with anything within the curly brackets treated as JavaScript and anything outside the brackets treated as a string:

使用模板文字,可以将表达式嵌入占位符中 。 占位符用${}表示,大括号内的所有内容均视为JavaScript,而括号内的所有内容均视为字符串:

const method = 'interpolation'
const dynamicString = `This string is using ${method}.`

When dynamicString is logged to the console, the console will show the following:

dynamicString登录到控制台后,控制台将显示以下内容:


Output
This string is using interpolation.

One common example of embedding values in a string might be for creating dynamic URLs. With concatenation, this can be cumbersome. For example, the following declares a function to generate an OAuth access string:

在字符串中嵌入值的一个常见示例可能是创建动态URL。 如果进行串联,则可能很麻烦。 例如,以下语句声明一个函数以生成OAuth访问字符串:

function createOAuthString(host, clientId, scope) {return host + '/login/oauth/authorize?client_id=' + clientId + '&scope=' + scope
}createOAuthString('https://github.com', 'abc123', 'repo,user')

Logging this function will yield the following URL to the console:

记录此功能将向控制台生成以下URL:


Output
https://github.com/login/oauth/authorize?client_id=abc123&scope=repo,user

Using string interpolation, you no longer have to keep track of opening and closing strings and concatenation operator placement. Here is the same example with template literals:

使用字符串插值,您不再需要跟踪打开和关闭字符串以及串联运算符的位置。 这是带有模板文字的相同示例:

function createOAuthString(host, clientId, scope) {return `${host}/login/oauth/authorize?client_id=${clientId}&scope=${scope}`
}createOAuthString('https://github.com', 'abc123', 'repo,user')

This will have the same output as the concatenation example:

这将具有与串联示例相同的输出:


Output
https://github.com/login/oauth/authorize?client_id=abc123&scope=repo,user

You can also use the trim() method on a template literal to remove any whitespace at the beginning or end of the string. For example, the following uses an arrow function to create an HTML <li> element with a customized link:

您还可以在模板文字上使用trim()方法删除字符串开头或结尾的任何空格。 例如,以下代码使用箭头功能创建带有自定义链接HTML <li>元素 :

const menuItem = (url, link) =>`
<li><a href="${url}">${link}</a>
</li>
`.trim()menuItem('https://google.com', 'Google')

The result will be trimmed of all the whitespace, ensuring that the element will be rendered correctly:

将修剪所有空白的结果,确保元素将正确呈现:


Output
<li><a href="https://google.com">Google</a>
</li>

Entire expressions can be interpolated, not just variables, such as in this example of the sum of two numbers:

可以插入整个表达式,而不仅仅是变量,例如在此示例中,两个数字之和:

const sum = (x, y) => x + y
const x = 5
const y = 100
const string = `The sum of ${x} and ${y} is ${sum(x, y)}.`console.log(string)

This code defines the sum function and the variables x and y, then uses both the function and the variables in a string. The logged result will show the following:

此代码定义sum函数以及变量xy ,然后在字符串中使用函数和变量。 记录的结果将显示以下内容:


Output
The sum of 5 and 100 is 105.

This can be particularly useful with ternary operators, which allow conditionals within a string:

这对于三元运算符特别有用,它允许在字符串中使用条件:

const age = 19
const message = `You can ${age < 21 ? 'not' : ''} view this page`
console.log(message)

The logged message here will change depnding on whether the value of age is over or under 21. Since it is 19 in this example, the following output will be logged:

这里记录的信息将改变depnding上的值是否age高于或低于21 。 由于在此示例中为19 ,因此将记录以下输出:


Output
You can not view this page

Now you have an idea of how template literals can be useful when used to interpolate expressions. The next section will take this a step further by examining tagged template literals to work with the expressions passed into placeholders.

现在,您将了解模板文字在用于插入表达式时如何有用。 下一部分将通过检查带标签的模板文字来处理传递给占位符的表达式,从而使这一步骤更进一步。

标记模板文字 (Tagged Template Literals)

An advanced feature of template literals is the use of tagged template literals, sometimes referred to as template tags. A tagged template starts with a tag function that parses a template literal, allowing you more control over manipulating and returning a dynamic string.

模板文字的高级功能是使用带标签的模板文字 ,有时也称为模板标签 。 带标签的模板从解析模板文字的标签函数开始,使您可以更好地控制操作和返回动态字符串。

In this example, you’ll create a tag function to use as the function operating on a tagged template. The string literals are the first parameter of the function, named strings here, and any expressions interpolated into the string are packed into the second parameter using rest parameters. You can console out the parameter to see what they will contain:

在此示例中,您将创建一个tag函数,用作在标记模板上运行的函数。 字符串文字是该函数的第一个参数,在此命名为strings ,插入到字符串中的任何表达式都使用rest参数打包到第二个参数中 。 您可以调出参数来查看它们将包含的内容:

function tag(strings, ...expressions) {console.log(strings)console.log(expressions)
}

Use the tag function as the tagged template function and parse the string as follows:

使用tag功能作为标记的模板功能,并按如下方式解析字符串:

const string = tag`This is a string with ${true} and ${false} and ${100} interpolated inside.`

Since you’re console logging strings and expressions, this will be the output:

由于您正在控制台记录stringsexpressions ,因此将是输出:


Output
(4) ["This is a string with ", " and ", " and ", " interpolated inside."
(3) [true, false, 100]

The first parameter, strings, is an array containing all the string literals:

第一个参数strings是包含所有字符串文字的数组 :

  • "This is a string with "

    "This is a string with "

  • " and "

    " and "

  • " and "

    " and "

  • " interpolated inside."

    " interpolated inside."

There is also a raw property available on this argument at strings.raw, which contains the strings without any escape sequences being processed. For example, /n would just be the character /n and not be escaped into a newline.

此参数在strings.raw上还有一个raw属性,其中包含未处理任何转义序列的字符串。 例如, /n只是字符/n而不会转义为换行符。

The second parameter, ...expressions, is a rest parameter array consisting of all the expressions:

第二个参数...expressions是一个由所有表达式组成的rest参数数组:

  • true

    true

  • false

    false

  • 100

    100

The string literals and expressions are passed as parameters to the tagged template function tag. Note that the tagged template does not need to return a string; it can operate on those values and return any type of value. For example, we can have the function ignore everything and return null, as in this returnsNull function:

字符串文字和表达式作为参数传递给加标签的模板函数tag 。 请注意,带标签的模板不需要返回字符串。 它可以对这些值进行运算,并返回任何类型的值。 例如,我们可以让函数忽略所有内容并返回null ,如下面的returnsNull函数所示:

function returnsNull(strings, ...expressions) {return null
}const string = returnsNull`Does this work?`
console.log(string)

Logging the string variable will return:

记录string变量将返回:


Output
null

An example of an action that can be performed in tagged templates is applying some change to both sides of each expression, such as if you wanted to wrap each expression in an HTML tag. Create a bold function that will add <strong> and </strong> to each expression:

可以在带标签的模板中执行的操作的一个示例是对每个表达式的两面都进行一些更改,例如是否要将每个表达式包装在HTML标记中。 创建一个bold函数,该函数将在每个表达式中添加<strong></strong>

function bold(strings, ...expressions) {let finalString = ''// Loop through all expressionsexpressions.forEach((value, i) => {finalString += `${strings[i]}<strong>${value}</strong>`})// Add the last string literalfinalString += strings[strings.length - 1]return finalString
}const string = bold`This is a string with ${true} and ${false} and ${100} interpolated inside.`console.log(string)

This code uses the forEach method to loop over the expressions array and add the bolding element:

此代码使用forEach方法遍历expressions数组并添加粗体元素:


Output
This is a string with <strong>true</strong> and <strong>false</strong> and <strong>100</strong> interpolated inside.

There are a few examples of tagged template literals in popular JavaScript libraries. The graphql-tag library uses the gql tagged template to parse GraphQL query strings into the abstract syntax tree (AST) that GraphQL understands:

流行JavaScript库中有一些标记模板文字的示例。 graphql-tag库使用gql标签模板将GraphQL查询字符串解析为GraphQL理解的抽象语法树(AST):

import gql from 'graphql-tag'// A query to retrieve the first and last name from user 5
const query = gql`{user(id: 5) {firstNamelastName}}
`

Another library that uses tagged template functions is styled-components, which allows you to create new React components from regular DOM elements and apply additional CSS styles to them:

另一个使用标签模板函数的库是styled-components ,它允许您从常规DOM元素创建新的React组件 ,并将其他CSS样式应用于它们:

import styled from 'styled-components'const Button = styled.button`color: magenta;
`// <Button> can now be used as a custom component

You can also use the built-in String.raw method on tagged template literals to prevent any escape sequences from being processed:

您还可以对标记的模板文字使用内置的String.raw方法,以防止处理任何转义序列:

const rawString = String.raw`I want to write /n without it being escaped.`
console.log(rawString)

This will log the following:

这将记录以下内容:


Output
I want to write /n without it being escaped.

结论 (Conclusion)

In this article, you reviewed single- and double-quoted string literals and you learned about template literals and tagged template literals. Template literals make a lot of common string tasks simpler by interpolating expressions in strings and creating multi-line strings without any concatenation or escaping. Template tags are also a useful advanced feature of template literals that many popular libraries have used, such as GraphQL and styled-components.

在本文中,您回顾了单引号和双引号的字符串文字,并了解了模板文字和带标签的模板文字。 通过插入字符串中的表达式并创建多行字符串而没有任何串联或转义,模板文字使许多常见的字符串任务变得更加简单。 模板标记还是许多常用库(例如GraphQL和styled-components使用的模板文字的有用的高级功能。

To learn more about strings in JavaScript, read How To Work with Strings in JavaScript and How To Index, Split, and Manipulate Strings in JavaScript.

要了解有关JavaScript中的字符串的更多信息,请阅读如何在JavaScript中使用字符串以及如何 在JavaScript中 索引,拆分和操作字符串 。

翻译自: https://www.digitalocean.com/community/tutorials/understanding-template-literals-in-javascript

javascript 模板

javascript 模板_了解JavaScript中的模板文字相关推荐

  1. ThinkPHP6 模板引擎普通标签中,模板引擎运算符函数,循环标签,判断标签的使用,及一些特殊标签

    ThinkPHP6 模板引擎普通标签中,模板引擎运算符函数,循环标签,判断标签的使用,及一些特殊标签 模板引擎支持普通标签和XML标签方式两种标签定义,分别用于不同的目的: 标签类型 描述 普通标签 ...

  2. 苹果cms10好看的模板_电脑手机自适应超简洁模板

    苹果cms10好看的模板_电脑手机自适应超简洁模板 自适应原创侧边栏系列苹果cmsv10简约模板DIY系列苹果cms模板案例版,经典边框设计风格大图片旋转,原创CSS框架风格库为视频网站设计,无残留代 ...

  3. 创建模板_在 GNOME 中创建文档模板 | Linux 中国

    导读:制作模板可以让你更快地开始写作新的文档. 本文字数:1305,阅读时长大约:1分钟https://linux.cn/article-12699-1.html作者:Alan Formy-duval ...

  4. javascript在第三个文本框中显示文字_一段中的个别文字,显示在目录中

    样例 说明 通常,目录中显示的文字是应用了标题样式的整段文字,而不是段落中的个别文字但有时,需要让个别文字,或者正文中根本不存在的文字,显示在目录中.要求:目录中只显示段落开头的摘要二字简述 设置 步 ...

  5. javascript教程_最好JavaScript教程

    javascript教程 JavaScript is the most widely used scripting language on Earth. And it has the largest ...

  6. 制作模板_年会邀请函制作免费模板

    点击上方蓝字关注我们在线制作 作为一年一次鼓舞士气,增强企业凝聚力的年会,可以让员工更好的在心理上和精神上与企业的核心价值观联系起来,也为企业来年带下一个好的基础. 年会是每年一次的重要会议,跟随着时 ...

  7. javascript 框架_克服JavaScript框架疲劳

    javascript 框架 by Tero Parviainen 通过Tero Parviainen 克服JavaScript框架疲劳 (Overcoming JavaScript Framework ...

  8. javascript原型_使用JavaScript的示例报告卡Web应用程序原型

    javascript原型 Hi! At times, beginners always find it hard getting the application of the theory they ...

  9. python 网站模板_使用Python抓取模板之家的CSS模板

    Python版本是2.7.9,在win8上测试成功,就是抓取有点慢,本来想用多线程的,有事就罢了.模板之家的网站上的url参数与页数不匹配,懒得去做分析了,就自己改代码中的url吧.大神勿喷! 代码如 ...

最新文章

  1. Linux ext2文件系统小结
  2. 让Windows下Git和TortoiseGit支持中文文件名/UTF-8
  3. 操作系统习题7—文件系统
  4. vector 中的元素去重
  5. violinplot如何看懂_一张图告诉你如何看懂个股大趋势
  6. python面向对象和面向过程_python--什么是面向对象和面向过程,对象的进化,什么是对象...
  7. Eclipse--java.lang.OutOfMemoryError: PermGen space
  8. NLPIR语义智能平台支持大数据个性化学习
  9. mysql 执行计划不对_mysql tokudb执行计划走的不准确案例
  10. OpenCV——无法打开“opencv2/opencv.hpp”文件
  11. Arduino -uno 核心板 之中级系列3 QAU04生日快乐歌实验
  12. 一张图看懂财务报表分析
  13. 如果你不释放MogaFX外汇,你将无法获得交易或投资
  14. 帝国php忘记密码,帝国cms7.5忘记登录密码以及多次登录失败被锁定终极解决办法-更新...
  15. Python前世今生
  16. 嗖的一下第二弹,这些好看的皮肤直接一键收下~~
  17. IT行业博客网站创新与创新(一)ITeye、CSDN、cnblog、ITpub博客网站的比较
  18. js强制保留两位小数
  19. java decvm_java – 如何使用-XX:UnlockDiagnosticVMOptions -XX:CompileCommand =打印选项与JVM HotSpot...
  20. 任天堂switch手柄怎么拆解图文教程 教你如何拆joycon

热门文章

  1. Intel VT学习笔记(二)—— VMXEVMXON
  2. 【项目管理】项目进度管理
  3. java银联在线支付开发_银联在线支付案例代码
  4. Lambda表达式和Stream类的使用
  5. 电脑投屏LED大屏颜色偏色问题解决
  6. Window: 换了固态硬盘装好系统后,为什么一直无法进入系统呢
  7. Spring Boot 核心注解?主要由哪几个注解组成?
  8. android 屏幕方向监听,Android如何监听屏幕旋转
  9. 基于uml的大学图书馆图书信息管理系统设计实验_全国大学最美图书馆排行!这个学校居然有按摩服务?!...
  10. 微博的大数据挖掘:知著、见微、晓意