示例 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 模板字面量支持。
另请阅读