我在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)

其他回答

我喜欢这种语法和含义:

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

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

总之,我在用户javascript编程(Opera 11.01)中尝试了两种方法:

这一个不起作用:在JavaScript中创建多行字符串这非常有效,我还找到了如何让它在Notepad++源代码视图中看起来很好:在JavaScript中创建多行字符串

所以我推荐Opera用户JS用户的工作方法。与作者所说的不同:

它不适用于萤火虫或歌剧;仅在IE、chrome和safari上。

它在歌剧11中确实有效。至少在用户JS脚本中。遗憾的是,我不能对个人答案发表评论,也不能对答案进行投票,我会立即这样做。如果可能,请有更高权限的人帮我做。

您可以使用标记的模板来确保获得所需的输出。

例如:

// 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'

带变量的多行字符串

var x = 1
string = string + `<label class="container">
                       <p>${x}</p>
                   </label>`;

你可以这样做。。。

var string = 'This is\n' +
'a multiline\n' + 
'string';