在 JavaScript 编写多行字符串
本教程介绍如何用 JavaScript 编写多行字符串。在 ES6 之前的时代,JavaScript 不直接支持多行字符串。有几种方法可以实现此目的,ES6 之前的方法还不太好,ES6 的方法是语法糖方法。我们将一一介绍所有这些方法。
我们可以将字符串分成多个子字符串,然后使用+
符号将它们连接在一起以获得完整的单个字符串。通过这种方式,我们可以将字符串分成多行,然后将它们同时放入一个字符串中。
const str ='This is DelftStack'+
' We make cool How to Tutorials'+
' &'+
' Make the life of other developers easier.';
输出:
"This is DelftStack We make cool How to Tutorials & Make the life of other developers easier."
在引入模板文字之前,这是最简单且最有前途的写多行字符串的方法,但是此方法无法将形成的字符串输出为多行字符串,必须通过在每行末尾附加一个\n
来实现。
我们可以在每行的末尾添加反斜杠,以在双引号/单引号内创建多行字符串,因为此字符有助于我们转义换行符。
const str ='This is DelftStack \
We make cool How to Tutorials \
& \
Make the life of other developers easier.';
输出:
"This is DelftStack We make cool How to Tutorials & Make the life of other developers easier."
因此,我们将字符串写成跨多行的形式,但又将统一的字符串组合在一起,这有助于我们实现目标,正确的显示输出和代码的可读性。但是并不总是希望我们可能希望即使显示时也将它们实际上分成多行。这可以通过在 ES6 中使用模板文字来实现。
模板文字是 ES6 引入的一种新方法,它可以帮助我们借助反引号(此字符`被称为反引号)来编写多行字符串。到目前为止,这是最好的解决方案,因为它不仅允许我们编写多行字符串,而且还以完全相同的方式打印它们,这是任何早期方法都无法实现的。
var str = `This is DelftStack
We make cool How to Tutorials
&
Make the life of other developers easier.
`
输出:
This is DelftStack
We make cool How to Tutorials
&
Make the life of other developers easier.
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。