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

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

当前回答

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

例如:

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

其他回答

出于对互联网的热爱,请使用字符串连接,并选择不使用ES6解决方案。ES6并不是全面支持的,很像CSS3,某些浏览器适应CSS3的移动速度很慢。使用简单的JavaScript,您的最终用户将感谢您。

例子:

var str=“这个世界既不是平的,也不是圆的。”+“一旦丢失将被发现”;

刚刚尝试了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);​

希望它有帮助!!

使用脚本标记:

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

我很惊讶我没有看到这一点,因为它在我测试过的任何地方都有效,并且对模板非常有用:

<script type="bogus" id="multi">
    My
    multiline
    string
</script>
<script>
    alert($('#multi').html());
</script>

有人知道有HTML但不起作用的环境吗?

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

干杯