我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?

text = <<"HERE"
This
Is
A
Multiline
String
HERE

当前回答

ES6的方法是使用模板文字:

const str = `This 

is 

a

multiline text`; 

console.log(str);

此处提供更多参考

其他回答

我喜欢这种语法和含义:

string = 'my long string...\n'
       + 'continue here\n'
       + 'and here.';

(但实际上不能视为多行字符串)

您可以使用+=连接字符串,似乎没有人回答,这将是可读的,也很整洁。。。像这样的东西

var hello = 'hello' +
            'world' +
            'blah';

也可以写成

var hello = 'hello';
    hello += ' world';
    hello += ' blah';

console.log(hello);

准确的

Ruby produce:“This\nIs\nMultiline\nString\n”-在JS下面生成完全相同的字符串

text=`此是A.多行一串`//测试console.log(JSON.stringify(文本));console.log(文本);

这是对朗尼最佳答案的改进,因为他的答案中的换行符与ruby输出中的位置不完全相同

在这里找到了很多过度设计的答案。我认为最好的两个答案是:

1:

 let str = `Multiline string.
            foo.
            bar.`

其最终记录:

Multiline string.
           foo.
           bar.  

2:

let str = `Multiline string.
foo.
bar.`

这会正确地记录它,但如果str嵌套在函数/对象等内部,则脚本文件中会很难看。:

Multiline string.
foo.
bar.

我非常简单的回答是用正则表达式正确记录str:

let str = `Multiline string.
           foo.
           bar.`.replace(/\n +/g, '\n');

请注意,这不是一个完美的解决方案,但如果您确定在新行(\n)之后至少会出现一个空格(+表示至少出现一次),则可以使用。它还可以与*(零或更多)一起使用。

您可以更明确地使用{n,},这意味着至少出现n次。

下选民:此代码仅供参考。

这已经在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>