JavaScript 程序:创建多行字符串

要理解此示例,您应了解以下 JavaScript 编程 主题


示例 1:使用 + 创建多行字符串

// program to create a multiline strings

// using the + operator
const message = 'This is a long message\n' + 
    'that spans across multiple lines\n' + 
    'in the code.'

console.log(message);

输出

This is a long message
that spans across multiple lines
in the code.

在上面的示例中,使用 + 运算符和 \n 创建了一个多行字符串。

转义字符 \n 用于换行。


示例 2:使用 \ 创建多行字符串

// program to create a multiline strings

// using the \ operator
const message = 'This is a long message\n \
that spans across multiple lines\n \
in the code.'

console.log(message);

输出

This is a long message
that spans across multiple lines
in the code.

在上面的示例中,使用 \ 创建了一个多行字符串。\n 用于换行。


示例 3:使用模板字面量创建多行字符串

// program to create a multiline strings

// using the template literal

const message = `This is a long message
that spans across multiple lines
in the code.`

console.log(message);

输出

This is a long message
that spans across multiple lines
in the code.

在上面的示例中,使用模板字面量 ` ` 来编写多行字符串。

模板字面量是在较新版本的 JavaScript (ES6) 中引入的。

某些浏览器可能不支持模板字面量。要了解更多信息,请访问 JavaScript 模板字面量支持


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战