我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
当前回答
至少在源代码方面,这是一种相当经济的方法:
function s() {
var args = [],index;
for (index = 0; index< arguments.length; index++) {
args.push (arguments [index]);
}
return args.join ("\n");
}
console.log (s (
"This is the first line",
"and this is the second",
"finally a third"
));
function s() {return arguments.join ("\n")}
如果“arguments”属性是一个正确的数组,当然会更好。
第二个版本可能使用“”来进行连接,当您想要控制非常长的字符串中的换行符时。
其他回答
您可以使用+=连接字符串,似乎没有人回答,这将是可读的,也很整洁。。。像这样的东西
var hello = 'hello' +
'world' +
'blah';
也可以写成
var hello = 'hello';
hello += ' world';
hello += ' blah';
console.log(hello);
实现这一点有多种方法
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>
`
这适用于IE、Safari、Chrome和Firefox:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div class="crazy_idea" thorn_in_my_side='<table border="0">
<tr>
<td ><span class="mlayouttablecellsdynamic">PACKAGE price $65.00</span></td>
</tr>
</table>'></div>
<script type="text/javascript">
alert($(".crazy_idea").attr("thorn_in_my_side"));
</script>
我认为这个解决方法应该适用于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>
干杯
在JavaScript中打印多行字符串的一种简单方法是使用由反引号(``)表示的模板文本(模板字符串)。还可以在模板字符串中使用变量,如(“name is${value}”)
你也可以
常量值=`multiline`const text=`这是一个${value}js中的字符串`;console.log(文本);