我在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(){/*\n”和“\n*/}”。
var multiline = function(string) { return string.toString().replace(/(^[^\n]*\n)|(\n\*\/\})/g, ""); };
console.log(multiline(function() {/*
Hello world!
I'm a multiline string!
Tada!
*/}));
我能看到的唯一缺陷是语法高亮显示。
编辑:如果我再向下滚动一点,我会看到这个答案完全一样:https://stackoverflow.com/a/5571069/916553
我想出了一个非常巧妙的方法来处理多行字符串。由于将函数转换为字符串也会返回函数内的任何注释,因此可以使用多行注释/**/将注释用作字符串。你只需要把两端修剪一下,你就有了你的绳子。
var myString = function(){/*
This is some
awesome multi-lined
string using a comment
inside a function
returned as a string.
Enjoy the jimmy rigged code.
*/}.toString().slice(14,-3)
alert(myString)
我的分机号码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();
在Javascrip中创建多行字符串最简单的方法是使用反引号(``)。这允许您创建多行字符串,在其中可以插入带有${variableName}的变量。
例子:
let name='Willem';假设年龄=26岁;让multilineString=`我的名字是:${name}我的年龄是:${age}`;console.log(multilineString);
兼容性:
它在ES6//es2015中介绍现在,所有主要浏览器供应商(internet explorer除外)都支持它
在此处查看Mozilla文档中的确切兼容性
下选民:此代码仅供参考。
这已经在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>