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

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

当前回答

模式text=<<“HERE”这是一个多行字符串HERE在js中是不可用的(我记得在我以前的Perl时代经常使用它)。

为了保持对复杂或长的多行字符串的监督,我有时使用数组模式:

var myString = 
   ['<div id="someId">',
    'some content<br />',
    '<a href="#someRef">someRefTxt</a>',
    '</div>'
   ].join('\n');

或者匿名者已经显示的模式(转义换行符),这可能是代码中的一个丑陋的块:

    var myString = 
       '<div id="someId"> \
some content<br /> \
<a href="#someRef">someRefTxt</a> \
</div>';

这是另一个奇怪但有效的“技巧”1:

var myString = (function () {/*
   <div id="someId">
     some content<br />
     <a href="#someRef">someRefTxt</a>
    </div>        
*/}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];

外部编辑:jsfiddle

ES20xx支持使用模板字符串跨多行生成字符串:

let str = `This is a text
    with multiple lines.
    Escapes are interpreted,
    \n is a newline.`;
let str = String.raw`This is a text
    with multiple lines.
    Escapes are not interpreted,
    \n is not a newline.`;

1注意:缩小/模糊代码后,这将丢失

其他回答

使用脚本标记:

添加<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>

我认为这个解决方法应该适用于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 myString = "First line" + "\n";
var myString = myString + "Second line" + "\n";
var myString = myString + "Third line" + "\n";

我的分机号码https://stackoverflow.com/a/15558082/80404.它需要格式为/*!任何多行注释*/where符号!用于防止缩小移除(至少适用于YUI压缩机)

Function.prototype.extractComment = function() {
    var startComment = "/*!";
    var endComment = "*/";
    var str = this.toString();

    var start = str.indexOf(startComment);
    var end = str.lastIndexOf(endComment);

    return str.slice(start + startComment.length, -(str.length - end));
};

例子:

var tmpl = function() { /*!
 <div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
    </ul>
 </div>
*/}.extractComment();