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

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

当前回答

我认为这个解决方法应该适用于IE、Chrome、Firefox、Safari和Opera-

使用jQuery:

<xmp id="unique_id" style="display:none;">
  Some plain text
  Both type of quotes :  " ' " And  ' " '
  JS Code : alert("Hello World");
  HTML Code : <div class="some_class"></div>
</xmp>
<script>
   alert($('#unique_id').html());
</script>

使用纯Javascript:

<xmp id="unique_id" style="display:none;">
  Some plain text
  Both type of quotes :  " ' " And  ' " '
  JS Code : alert("Hello World");
  HTML Code : <div class="some_class"></div>
</xmp>
<script>
   alert(document.getElementById('unique_id').innerHTML);
</script>

干杯

其他回答

还要注意,当在每行末尾使用前向反斜杠在多行上扩展字符串时,前向反斜线后面的任何额外字符(主要是空格、制表符和错误添加的注释)都会导致意外的字符错误,我花了一个小时才发现

var string = "line1\  // comment, space or tabs here raise error
line2";

它不是非常优雅,但对我来说足够干净:

var myString = "First line" + "\n";
var myString = myString + "Second line" + "\n";
var myString = myString + "Third line" + "\n";

准确的

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

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

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

你可以这样做。。。

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

至少在源代码方面,这是一种相当经济的方法:

function s() {
    var args = [],index;
    for (index = 0; index< arguments.length; index++) {
        args.push (arguments [index]);
    }
    return args.join ("\n");
}
console.log (s (
    "This is the first line",
    "and this is the second",
    "finally a third"
));

function s() {return arguments.join ("\n")} 

如果“arguments”属性是一个正确的数组,当然会更好。

第二个版本可能使用“”来进行连接,当您想要控制非常长的字符串中的换行符时。