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

干杯

其他回答

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

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”属性是一个正确的数组,当然会更好。

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

准确的

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

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

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

ES6允许您使用反勾号在多行上指定字符串。它被称为模板文字。这样地:

var multilineString = `One line of text
    second line of text
    third line of text
    fourth line of text`;

在NodeJS中使用backtick,Chrome、Firefox、Edge、Safari和Opera都支持它。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

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

例如:

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

刚刚尝试了Anonymous的答案,发现这里有一个小技巧,如果反斜杠后面有空格,它就不起作用了因此,以下解决方案不起作用-

var x = { test:'<?xml version="1.0"?>\ <-- One space here
            <?mso-application progid="Excel.Sheet"?>' 
};

但当空间被移除时,它会起作用-

var x = { test:'<?xml version="1.0"?>\<-- No space here now
          <?mso-application progid="Excel.Sheet"?>' 
};

alert(x.test);​

希望它有帮助!!