多行字符串是跨多行的 JavaScript 字符串。在程序中使用多行字符串使其更易于阅读和维护。在 JavaScript 中,创建多行字符串的最简单方法是使用模板文字(模板字符串)。模板文本是在 ECMAScript 2015 (ES6) 中引入的。在引入模板文字之前,多行字符串是通过使用 + 运算符连接多个字符串来创建的。
在 JavaScript 中,字符串是包含字母、数字和特殊字符的字符序列。我们可以使用单引号 (')、双引号 (“) 或反引号 (') 字符创建字符串。
使用模板文本创建多行字符串
模板文字( template literals)是在 JavaScript 中创建多行字符串的最佳方式。模板文字用反引号 (') 字符括起来。模板文本包含字符串和占位符。模板文本有时也称为模板字符串(template strings)。
模板文字的一个简单示例如下 -
`This is a template literal enclosed by backtick characters.`
现在让我们使用模板文字创建一个多行字符串 -
let multilineString = `This is a multiline
string created using
template literal.`
在上面的 JavaScript 代码片段中,我们创建了一个包含三行的多行字符串。我们将此多行字符串分配给名为 的变量。multilineString
例在下面的示例中,我们使用模板文字创建了一个多行字符串,并在 Web 控制台中显示了该字符串。
let mulString = `This is a multiline
string created using
template literal.`;
console.log(mulString);
输出
string created using
template literal.
例
在下面的示例中,我们尝试在网页上使用模板文本显示多行字符串 crate。我们使用 <br> 来换行。
<!DOCTYPE html>
<html>
<body>
<p id = "output"></p>
<script>
let mulString = `This is a multine <br>
string created using template literal <br>
and displayed on the webpage.`;
document.getElementById("output").innerHTML = mulString;
</script>
</body>
</html>
输出
string created using template literal
and displayed on the webpage.
使用 + 运算符创建多行字符串
我们还可以通过使用 + 运算符连接各个字符串,在 JavaScript 中创建多行字符串。要创建换行符,我们可以使用转义字符 \n 或 <br>。
您可以连接使用单引号或双引号定义的字符串。
让我们看一下以下示例 -
例在此示例中,我们通过连接三个单独的字符串创建了一个多行字符串。我们在各个字符串的末尾使用转义字符 (\n) 来换行。
let mulString = "This is a multiline string\n" +
"created by concatenating the individual strings\n" +
"and using \\n to break the line.";
console.log(mulString);
输出
created by concatenating the individual strings
and using \n to break the line.
例
在下面的示例中,我们通过连接三个字符串创建了一个多行字符串。我们用 <br> 来打破界限。
<!DOCTYPE html>
<html>
<body>
<p id = "output"></p>
<script>
let mulString = "This is a multiline string <br>" +
"created by concatenating the individual strings<br>" +
"and line break.";
document.getElementById("output").innerHTML = mulString;
</script>
</body>
</html>
输出
created by concatenating the individual strings
and line break.
使用 \ 运算符创建多行字符串
我们可以使用反斜杠 (\) 运算符在 JavaScript 中创建多行字符串。我们可以使用转义字符 (\n) 来换行。
例请尝试以下 JavaScript 示例 -
let mulString = "This is a multiline string\n\
created using the backslash operator\n\
and escape character to break the line.";
console.log(mulString);
输出
created using the backslash operator
and escape character to break the line.
例
在下面的示例中,我们使用反斜杠 (\) 运算符创建了一个多行字符串。为了进行换行,我们使用了 <br>。
<!DOCTYPE html>
<html>
<body>
<p id = "output"></p>
<script>
let mulString = "This is first line of the multiline string <br>\
This is second line of the multiline string <br> \
This is the last line of multiline string.";
document.getElementById("output").innerHTML = mulString;
</script>
</body>
</html>
输出
This is second line of the multiline string
This is the last line of multiline string.

