在 JavaScript 中创建多行字符串 [英] Creating multiline strings in JavaScript
问题描述
我在 Ruby 中有以下代码.我想将此代码转换为 JavaScript.JS中的等价代码是什么?
text = <<
更新:
ECMAScript 6 (ES6) 引入了一种新的文字类型,即 模板文字.它们有很多特征,变量插值等等,但对于这个问题最重要的是,它们可以是多行的.
模板文字由反引号分隔:
var html = `<div><span>这里有一些 HTML</span>
`;
(注意:我不提倡在字符串中使用 HTML)
浏览器支持没问题,但你可以使用
原始 ES5 答案:
Javascript 没有 here-document 语法.但是,您可以转义文字换行符,这很接近:
"foo 酒吧"
I have the following code in Ruby. I want to convert this code into JavaScript. What is the equivalent code in JS?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
Update:
ECMAScript 6 (ES6) introduces a new type of literal, namely template literals. They have many features, variable interpolation among others, but most importantly for this question, they can be multiline.
A template literal is delimited by backticks:
var html = `
<div>
<span>Some HTML here</span>
</div>
`;
(Note: I'm not advocating to use HTML in strings)
Browser support is OK, but you can use transpilers to be more compatible.
Original ES5 answer:
Javascript doesn't have a here-document syntax. You can escape the literal newline, however, which comes close:
"foo
bar"
这篇关于在 JavaScript 中创建多行字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!