我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
当前回答
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');
容易的
其他回答
ES6允许您使用反勾号在多行上指定字符串。它被称为模板文字。这样地:
var multilineString = `One line of text
second line of text
third line of text
fourth line of text`;
在NodeJS中使用backtick,Chrome、Firefox、Edge、Safari和Opera都支持它。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
带变量的多行字符串
var x = 1
string = string + `<label class="container">
<p>${x}</p>
</label>`;
ES6的方法是使用模板文字:
const str = `This
is
a
multiline text`;
console.log(str);
此处提供更多参考
我喜欢这种语法和含义:
string = 'my long string...\n'
+ 'continue here\n'
+ 'and 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>