我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
当前回答
您可以使用TypeScript(JavaScript SuperSet),它支持多行字符串,并将文件向下转换为纯JavaScript而无需开销:
var templates = {
myString: `this is
a multiline
string`
}
alert(templates.myString);
如果您想用普通JavaScript实现同样的功能:
var templates =
{
myString: function(){/*
This is some
awesome multi-lined
string using a comment
inside a function
returned as a string.
Enjoy the jimmy rigged code.
*/}.toString().slice(14,-3)
}
alert(templates.myString)
请注意,iPad/Safari不支持“functionName.toString()”
如果您有很多遗留代码,也可以在TypeScript中使用纯JavaScript变量(用于清理):
interface externTemplates
{
myString:string;
}
declare var templates:externTemplates;
alert(templates.myString)
您可以使用普通JavaScript变体中的多行字符串对象,将模板放入另一个文件中(可以合并到捆绑包中)。
您可以在以下位置尝试TypeScripthttp://www.typescriptlang.org/Playground
其他回答
模式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>
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
ES6的方法是使用模板文字:
const str = `This
is
a
multiline text`;
console.log(str);
此处提供更多参考
至少在源代码方面,这是一种相当经济的方法:
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”属性是一个正确的数组,当然会更好。
第二个版本可能使用“”来进行连接,当您想要控制非常长的字符串中的换行符时。