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

干杯

其他回答

这适用于IE、Safari、Chrome和Firefox:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div class="crazy_idea" thorn_in_my_side='<table  border="0">
                        <tr>
                            <td ><span class="mlayouttablecellsdynamic">PACKAGE price $65.00</span></td>
                        </tr>
                    </table>'></div>
<script type="text/javascript">
    alert($(".crazy_idea").attr("thorn_in_my_side"));
</script>

在这里找到了很多过度设计的答案。我认为最好的两个答案是:

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

您可以使用+=连接字符串,似乎没有人回答,这将是可读的,也很整洁。。。像这样的东西

var hello = 'hello' +
            'world' +
            'blah';

也可以写成

var hello = 'hello';
    hello += ' world';
    hello += ' blah';

console.log(hello);

我认为这个解决方法应该适用于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>

干杯

JavaScript从未有过处理多行字符串的真正好方法,直到2015年引入ES6以及模板文本。

模板文本是由反引号(``)分隔的字符串,而不是普通的单引号(“”)/双引号(““”)分隔符。