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

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

当前回答

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

const str = `This 

is 

a

multiline text`; 

console.log(str);

此处提供更多参考

其他回答

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

例如:

// 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 string = "line1\  // comment, space or tabs here raise error
line2";

如果恰好在Node中运行,则可以使用fs模块从文件中读入多行字符串:

var diagram;
var fs = require('fs');
fs.readFile( __dirname + '/diagram.txt', function (err, data) {
  if (err) {
    throw err; 
  }
  diagram = data.toString();
});

在JavaScript中打印多行字符串的一种简单方法是使用由反引号(``)表示的模板文本(模板字符串)。还可以在模板字符串中使用变量,如(“name is${value}”)

你也可以

常量值=`multiline`const text=`这是一个${value}js中的字符串`;console.log(文本);

我通过输出一个div,使其隐藏,并在需要时通过jQuery调用div id来解决这个问题。

e.g.

<div id="UniqueID" style="display:none;">
     Strings
     On
     Multiple
     Lines
     Here
</div>

然后,当我需要获取字符串时,我只需使用以下jQuery:

$('#UniqueID').html();

它会在多行上返回我的文本。如果我打电话

alert($('#UniqueID').html());

我得到: