我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
当前回答
规则是:当在字符串中时,在需要换行的地方使用;您不必在JavaScript之前或之后放置空格,JavaScript的解释器足够聪明,可以知道不可打印字符表示的长度。
其他回答
有这样一个图书馆,它很漂亮:
https://github.com/sindresorhus/multiline
之前
var str = '' +
'<!doctype html>' +
'<html>' +
' <body>' +
' <h1>❤ unicorns</h1>' +
' </body>' +
'</html>' +
'';
之后
var str = multiline(function(){/*
<!doctype html>
<html>
<body>
<h1>❤ unicorns</h1>
</body>
</html>
*/});
规则是:当在字符串中时,在需要换行的地方使用;您不必在JavaScript之前或之后放置空格,JavaScript的解释器足够聪明,可以知道不可打印字符表示的长度。
你可以这样做。。。
var string = 'This is\n' +
'a multiline\n' +
'string';
我认为这个解决方法应该适用于IE、Chrome、Firefox、Safari和Opera-
使用jQuery:
<xmp id="unique_id" style="display:none;">
Some plain text
Both type of quotes : " ' " And ' " '
JS Code : alert("Hello World");
HTML Code : <div class="some_class"></div>
</xmp>
<script>
alert($('#unique_id').html());
</script>
使用纯Javascript:
<xmp id="unique_id" style="display:none;">
Some plain text
Both type of quotes : " ' " And ' " '
JS Code : alert("Hello World");
HTML Code : <div class="some_class"></div>
</xmp>
<script>
alert(document.getElementById('unique_id').innerHTML);
</script>
干杯
实现这一点有多种方法
1.斜线拼接
var MultiLine= '1\
2\
3\
4\
5\
6\
7\
8\
9';
2.规则串联
var MultiLine = '1'
+'2'
+'3'
+'4'
+'5';
3.数组连接串联
var MultiLine = [
'1',
'2',
'3',
'4',
'5'
].join('');
就性能而言,斜杠串联(第一个)是最快的。
有关性能的更多详细信息,请参阅本测试用例
更新:
使用ES2015,我们可以利用其模板字符串功能。有了它,我们只需要使用反引号来创建多行字符串
例子:
`<h1>{{title}}</h1>
<h2>{{hero.name}} details!</h2>
<div><label>id: </label>{{hero.id}}</div>
<div><label>name: </label>{{hero.name}}</div>
`