我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
当前回答
javascript中的等效值为:
var text = `
This
Is
A
Multiline
String
`;
这是规格。请参阅本页底部的浏览器支持。这里也有一些例子。
其他回答
在这里找到了很多过度设计的答案。我认为最好的两个答案是:
1:
let str = `Multiline string.
foo.
bar.`
其最终记录:
Multiline string.
foo.
bar.
2:
let str = `Multiline string.
foo.
bar.`
这会正确地记录它,但如果str嵌套在函数/对象等内部,则脚本文件中会很难看。:
Multiline string.
foo.
bar.
我非常简单的回答是用正则表达式正确记录str:
let str = `Multiline string.
foo.
bar.`.replace(/\n +/g, '\n');
请注意,这不是一个完美的解决方案,但如果您确定在新行(\n)之后至少会出现一个空格(+表示至少出现一次),则可以使用。它还可以与*(零或更多)一起使用。
您可以更明确地使用{n,},这意味着至少出现n次。
我这样编程:
sys = {
layout: null,
makeLayout: function (obCLS) {
this.layout = $('<div />').addClass('editor').appendTo($(obCLS)).append(
/* Cargador */
/* @this.layout.find('> div:nth-of-child(1)'); */
'<div>' +
' <p>Seleccione la imagen que desea procesar.</p>' +
' <input type="button" value="Seleccionar" class="btn btn-xlarge btn-success" />' +
' <span></span>' +
'</div>' +
/* Cargador - Progreso */
/* @this.layout.find('> div:nth-of-child(2)'); */
'<div>' +
' <div>' +
' <div></div>' +
' <div>' +
' <div></div>' +
' </div>' +
' </div>' +
'</div>' +
/* Editor */
/* @this.layout.find('> div:nth-of-child(3)');
* @sidebar = this.layout.find('> div:nth-of-child(3) > div > div > div:nth-of-type(1)');
* @body = this.layout.find('> div:nth-of-child(3) > div > div > div:nth-of-type(2) > div'); */
'<div>' +
' <div>' +
' <div>' +
' <div></div>' +
' <div>' +
' <div></div>' +
' </div>' +
' </div>' +
' </div>' +
'</div>'
);
}
}
sys.makeLayout('#div');
带变量的多行字符串
var x = 1
string = string + `<label class="container">
<p>${x}</p>
</label>`;
至少在源代码方面,这是一种相当经济的方法:
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”属性是一个正确的数组,当然会更好。
第二个版本可能使用“”来进行连接,当您想要控制非常长的字符串中的换行符时。
实现这一点有多种方法
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>
`