我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
当前回答
使用脚本标记:
添加<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>
其他回答
总之,我在用户javascript编程(Opera 11.01)中尝试了两种方法:
这一个不起作用:在JavaScript中创建多行字符串这非常有效,我还找到了如何让它在Notepad++源代码视图中看起来很好:在JavaScript中创建多行字符串
所以我推荐Opera用户JS用户的工作方法。与作者所说的不同:
它不适用于萤火虫或歌剧;仅在IE、chrome和safari上。
它在歌剧11中确实有效。至少在用户JS脚本中。遗憾的是,我不能对个人答案发表评论,也不能对答案进行投票,我会立即这样做。如果可能,请有更高权限的人帮我做。
刚刚尝试了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);
希望它有帮助!!
您可以使用标记的模板来确保获得所需的输出。
例如:
// 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'
还要注意,当在每行末尾使用前向反斜杠在多行上扩展字符串时,前向反斜线后面的任何额外字符(主要是空格、制表符和错误添加的注释)都会导致意外的字符错误,我花了一个小时才发现
var string = "line1\ // comment, space or tabs here raise error
line2";
javascript中的等效值为:
var text = `
This
Is
A
Multiline
String
`;
这是规格。请参阅本页底部的浏览器支持。这里也有一些例子。