示例 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 模板文字支持。