我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
当前回答
我喜欢这种语法和含义:
string = 'my long string...\n'
+ 'continue here\n'
+ 'and here.';
(但实际上不能视为多行字符串)
其他回答
javascript中的等效值为:
var text = `
This
Is
A
Multiline
String
`;
这是规格。请参阅本页底部的浏览器支持。这里也有一些例子。
您可以在纯JavaScript中使用多行字符串。
此方法基于函数的序列化,该序列化被定义为依赖于实现。它在大多数浏览器中都能工作(见下文),但不能保证它在未来仍能工作,所以不要依赖它。
使用以下功能:
function hereDoc(f) {
return f.toString().
replace(/^[^\/]+\/\*!?/, '').
replace(/\*\/[^\/]+$/, '');
}
这里可以有这样的文档:
var tennysonQuote = hereDoc(function() {/*!
Theirs not to make reply,
Theirs not to reason why,
Theirs but to do and die
*/});
该方法已在以下浏览器中成功测试(未提及=未测试):
即4-10歌剧9.50-12(不在9-)Safari 4-6(不在3-中)铬1-45Firefox 17-21(非16-)Rekonq 0.7.0-0.8.0Konqueror 4.7.4不支持
不过,要小心你的缩小镜。它倾向于删除评论。对于YUI压缩程序,以/*开头的注释!(像我用过的那个)将被保留。
我认为真正的解决方案是使用CoffeeScript。
ES6 UPDATE:您可以使用backtick代替创建带有注释的函数,并在注释上运行toString。正则表达式需要更新为仅删除空格。您还可以使用字符串原型方法来执行此操作:
let foo = `
bar loves cake
baz loves beer
beer loves people
`.removeIndentation()
应该有人编写此.removeIndentation字符串方法…;)
有这样一个图书馆,它很漂亮:
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>
*/});
我喜欢这种语法和含义:
string = 'my long string...\n'
+ 'continue here\n'
+ 'and here.';
(但实际上不能视为多行字符串)
我的分机号码https://stackoverflow.com/a/15558082/80404.它需要格式为/*!任何多行注释*/where符号!用于防止缩小移除(至少适用于YUI压缩机)
Function.prototype.extractComment = function() {
var startComment = "/*!";
var endComment = "*/";
var str = this.toString();
var start = str.indexOf(startComment);
var end = str.lastIndexOf(endComment);
return str.slice(start + startComment.length, -(str.length - end));
};
例子:
var tmpl = function() { /*!
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
</ul>
</div>
*/}.extractComment();