JavaScript 多行字符串

2025年3月29日 | 阅读 4 分钟

在 JavaScript 中,字符串操作易于学习但难于精通。早期,JavaScript 不支持多行字符串。2015 年后,ES6 (ECMAScript 6) 引入了字符串字面量,支持多行字符串。

现在,有几种方法可以处理多行字符串。在本章中,我们将逐一讨论这些不同的多行字符串处理方法。

以下是几种使用多行字符串的方法

方法 1

这是 JavaScript 中在多行中显示字符串文本的最简单方法。在 document.write() 函数中使用换行符 (<br>) 或 HTML 来从新行开始文本。

示例

这是使用 JavaScript 编程实现多行字符串的实际示例

复制代码

输出

执行此代码时,将在网页上显示三个文本字符串,它们将使用 HTML 的换行符 (<br>) 进行分隔。

This is first line display using JavaScript.
This is second line and divided using break line tab of HTML.
Now, we again printed another new line.

示例 2:连接单个字符串

在此示例中,我们将使用 JavaScript 编程简单地打印多行字符串,而无需任何换行符

复制代码

输出

执行此代码时,将在网页上显示两个文本段落,它们将使用 HTML 的换行符 (<br>) 进行分隔。

TpointTech is a website of technologies, which provides tutorials of different technologies and tools. Here you will get tutorials in detail 'like theory as well as practical implementation.
We will try to provide you the best knowledge from our side. 'Student, teachers, and industry professionals can learn from here.

示例 3

这是使用 JavaScript 编程打印多行文本的简单示例。在这里,我们只使用了 HTML <br> 标签来将句子分成多行

复制代码

输出

执行此代码时,将在网页上显示三个段落,它们将使用 HTML 的换行符 (<br>) 进行分隔。

JavaScript is a programming language that is popular for web development at the client-side execution. This language is very light-weighted mostly used to put validations, so they check at client-side. 
Nowadays, it is very trending in market for web development.
As it also allows dynamic execution of code.

方法 2:您还可以将文本字符串放在 <p> 或 <b> 或 标题 标签 (<h1> 到 <h6>) 中,以将它们分成多行或段落。请参见下面的代码

复制代码

输出

上面输入的行将显示在多个新行中。这些行使用段落和粗体标签从新行开始。

This is first line of the paragraph. 
This text will show you in bold letters in next line. 
Now, it is again a simple text line.

方法 3:在此方法中,我们将打印一个多行字符串。这主要在您想要写段落时使用。

示例

您可以在多个 HTML 标签内编写多行文本,以清楚地理解 段落。请参考示例

复制代码

输出

执行上述代码将在网页上显示输出。请参见下面的响应;您会看到一个 Display Multiline 按钮,用于显示文本字符串。

JavaScript multi-line String

单击此 Display Multiline 按钮,文本字符串将以多行显示。请参见下面的输出

JavaScript multi-line String