我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
当前回答
我通过输出一个div,使其隐藏,并在需要时通过jQuery调用div id来解决这个问题。
e.g.
<div id="UniqueID" style="display:none;">
Strings
On
Multiple
Lines
Here
</div>
然后,当我需要获取字符串时,我只需使用以下jQuery:
$('#UniqueID').html();
它会在多行上返回我的文本。如果我打电话
alert($('#UniqueID').html());
我得到:
其他回答
至少在源代码方面,这是一种相当经济的方法:
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”属性是一个正确的数组,当然会更好。
第二个版本可能使用“”来进行连接,当您想要控制非常长的字符串中的换行符时。
使用脚本标记:
添加<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>
2015年更新:现在已经过了六年:大多数人使用模块加载器,主要模块系统都有加载模板的方法。它不是内联的,但最常见的多行字符串类型是模板,无论如何,模板应该被排除在JS之外。
require.js:'需要文本'。
使用require.js“text”插件,在template.html中使用多行模板
var template = require('text!template.html')
NPM/browserify:“brfs”模块
Browserify使用“brfs”模块加载文本文件。这实际上会将模板构建到捆绑的HTML中。
var fs = require("fs");
var template = fs.readFileSync(template.html', 'utf8');
容易的
规则是:当在字符串中时,在需要换行的地方使用;您不必在JavaScript之前或之后放置空格,JavaScript的解释器足够聪明,可以知道不可打印字符表示的长度。
带变量的多行字符串
var x = 1
string = string + `<label class="container">
<p>${x}</p>
</label>`;