我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
当前回答
您可以使用标记的模板来确保获得所需的输出。
例如:
// 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'
其他回答
您可以在纯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字符串方法…;)
下选民:此代码仅供参考。
这已经在Mac上的Fx 19和Chrome 24中进行了测试
DEMO
var new_comment/*<<<(英)<li class=“photobooth comment”><span class=“username”><a href=“#”>您</a>:</span><span class=“comment text”>$文本</span>@<span class=“comment time”>第二天</span>前</li>(英)*///注意,这里的脚本标记被硬编码为FIRST标记new_comment=document.currentScript.innerHTML.split(“EOF”)[1];document.querySelector(“ul”).innerHTML=new_comment.replace(“$text”,“这是动态创建的文本”);<ul></ul>
如果您愿意使用转义换行符,它们可以很好地使用。它看起来像带有页面边框的文档。
您可以使用+=连接字符串,似乎没有人回答,这将是可读的,也很整洁。。。像这样的东西
var hello = 'hello' +
'world' +
'blah';
也可以写成
var hello = 'hello';
hello += ' world';
hello += ' blah';
console.log(hello);
我的分机号码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();