我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
当前回答
ES6的方法是使用模板文字:
const str = `This
is
a
multiline text`;
console.log(str);
此处提供更多参考
其他回答
您可以使用标记的模板来确保获得所需的输出。
例如:
// Merging multiple whitespaces and trimming the output
const t = (strings) => { return strings.map((s) => s.replace(/\s+/g, ' ')).join("").trim() }
console.log(t`
This
Is
A
Multiline
String
`);
// Output: 'This Is A Multiline String'
// Similar but keeping whitespaces:
const tW = (strings) => { return strings.map((s) => s.replace(/\s+/g, '\n')).join("").trim() }
console.log(tW`
This
Is
A
Multiline
String
`);
// Output: 'This\nIs\nA\nMultiline\nString'
您可以使用+=连接字符串,似乎没有人回答,这将是可读的,也很整洁。。。像这样的东西
var hello = 'hello' +
'world' +
'blah';
也可以写成
var hello = 'hello';
hello += ' world';
hello += ' blah';
console.log(hello);
它不是非常优雅,但对我来说足够干净:
var myString = "First line" + "\n";
var myString = myString + "Second line" + "\n";
var myString = myString + "Third line" + "\n";
javascript中的等效值为:
var text = `
This
Is
A
Multiline
String
`;
这是规格。请参阅本页底部的浏览器支持。这里也有一些例子。
刚刚尝试了Anonymous的答案,发现这里有一个小技巧,如果反斜杠后面有空格,它就不起作用了因此,以下解决方案不起作用-
var x = { test:'<?xml version="1.0"?>\ <-- One space here
<?mso-application progid="Excel.Sheet"?>'
};
但当空间被移除时,它会起作用-
var x = { test:'<?xml version="1.0"?>\<-- No space here now
<?mso-application progid="Excel.Sheet"?>'
};
alert(x.test);
希望它有帮助!!