我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
当前回答
我想出了一个非常巧妙的方法来处理多行字符串。由于将函数转换为字符串也会返回函数内的任何注释,因此可以使用多行注释/**/将注释用作字符串。你只需要把两端修剪一下,你就有了你的绳子。
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)
其他回答
它不是非常优雅,但对我来说足够干净:
var myString = "First line" + "\n";
var myString = myString + "Second line" + "\n";
var myString = myString + "Third line" + "\n";
带变量的多行字符串
var x = 1
string = string + `<label class="container">
<p>${x}</p>
</label>`;
我认为这个解决方法应该适用于IE、Chrome、Firefox、Safari和Opera-
使用jQuery:
<xmp id="unique_id" style="display:none;">
Some plain text
Both type of quotes : " ' " And ' " '
JS Code : alert("Hello World");
HTML Code : <div class="some_class"></div>
</xmp>
<script>
alert($('#unique_id').html());
</script>
使用纯Javascript:
<xmp id="unique_id" style="display:none;">
Some plain text
Both type of quotes : " ' " And ' " '
JS Code : alert("Hello World");
HTML Code : <div class="some_class"></div>
</xmp>
<script>
alert(document.getElementById('unique_id').innerHTML);
</script>
干杯
至少在源代码方面,这是一种相当经济的方法:
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”属性是一个正确的数组,当然会更好。
第二个版本可能使用“”来进行连接,当您想要控制非常长的字符串中的换行符时。
您可以在纯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字符串方法…;)