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

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

当前回答

准确的

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

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

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

其他回答

如果您愿意使用转义换行符,它们可以很好地使用。它看起来像带有页面边框的文档。

准确的

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次。

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

例如:

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