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

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

e.g.

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

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

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

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

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

我得到:

我的基于数组的字符串连接版本:

var c = []; //c stands for content
c.push("<div id='thisDiv' style='left:10px'></div>");
c.push("<div onclick='showDo(\'something\');'></div>");
$(body).append(c.join('\n'));

这对我来说效果很好,尤其是当我经常将值插入到以这种方式构建的html中时。但它有很多局限性。缩进会很好。不用处理嵌套的引号真的很好,只是它的笨重让我很困扰。

要添加到数组中的.push()是否占用了大量时间?请参阅此相关答案:

(JavaScript开发人员不使用Array.push()有什么原因吗?)

在查看了这些(相反的)测试运行之后,看起来.push()对于不太可能增长超过100个项目的字符串数组是很好的-我将避免使用它,而支持对较大数组进行索引加法。

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

const str = `This 

is 

a

multiline text`; 

console.log(str);

此处提供更多参考