我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
当前回答
JavaScript从未有过处理多行字符串的真正好方法,直到2015年引入ES6以及模板文本。
模板文本是由反引号(``)分隔的字符串,而不是普通的单引号(“”)/双引号(““”)分隔符。
其他回答
如果恰好在Node中运行,则可以使用fs模块从文件中读入多行字符串:
var diagram;
var fs = require('fs');
fs.readFile( __dirname + '/diagram.txt', function (err, data) {
if (err) {
throw err;
}
diagram = data.toString();
});
我很惊讶我没有看到这一点,因为它在我测试过的任何地方都有效,并且对模板非常有用:
<script type="bogus" id="multi">
My
multiline
string
</script>
<script>
alert($('#multi').html());
</script>
有人知道有HTML但不起作用的环境吗?
我认为这个解决方法应该适用于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>
干杯
如果您愿意使用转义换行符,它们可以很好地使用。它看起来像带有页面边框的文档。
您可以使用+=连接字符串,似乎没有人回答,这将是可读的,也很整洁。。。像这样的东西
var hello = 'hello' +
'world' +
'blah';
也可以写成
var hello = 'hello';
hello += ' world';
hello += ' blah';
console.log(hello);