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

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

当前回答

你可以这样做。。。

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

其他回答

使用脚本标记:

添加<script></script>块,其中包含head标记中的多行文本;按原样获取多行文本…(注意文本编码:UTF-8、ASCII)<脚本>//纯javascriptvar text=document.getElementById(“mySoapMessage”).innerHTML;//使用JQuery的文档做好安全准备$(文档).ready(函数){var text=$(“#mySoapMessage”).html();});</script><script id=“mySoapMessage”type=“text/plain”><soapenv:Envelope xmlns:soapenv=“http://schemas.xmlsoap.org/soap/envelope/“xmlns:typ=”。。。"><soapenv:Header/><soapenv:Body><typ:getConvocatosElement>...</typ:getConvocatosElement></soapenv:Body></soapenv:信封><!-- 此注释将出现在字符串-->中//呃哦,javascript注释。。。SOAP请求将失败</script>

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

e.g.

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

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

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

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

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

我得到:

我喜欢这种语法和含义:

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

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

出于对互联网的热爱,请使用字符串连接,并选择不使用ES6解决方案。ES6并不是全面支持的,很像CSS3,某些浏览器适应CSS3的移动速度很慢。使用简单的JavaScript,您的最终用户将感谢您。

例子:

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