我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
当前回答
如果恰好在Node中运行,则可以使用fs模块从文件中读入多行字符串:
var diagram;
var fs = require('fs');
fs.readFile( __dirname + '/diagram.txt', function (err, data) {
if (err) {
throw err;
}
diagram = data.toString();
});
其他回答
下选民:此代码仅供参考。
这已经在Mac上的Fx 19和Chrome 24中进行了测试
DEMO
var new_comment/*<<<(英)<li class=“photobooth comment”><span class=“username”><a href=“#”>您</a>:</span><span class=“comment text”>$文本</span>@<span class=“comment time”>第二天</span>前</li>(英)*///注意,这里的脚本标记被硬编码为FIRST标记new_comment=document.currentScript.innerHTML.split(“EOF”)[1];document.querySelector(“ul”).innerHTML=new_comment.replace(“$text”,“这是动态创建的文本”);<ul></ul>
至少在源代码方面,这是一种相当经济的方法:
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”属性是一个正确的数组,当然会更好。
第二个版本可能使用“”来进行连接,当您想要控制非常长的字符串中的换行符时。
我这样编程:
sys = {
layout: null,
makeLayout: function (obCLS) {
this.layout = $('<div />').addClass('editor').appendTo($(obCLS)).append(
/* Cargador */
/* @this.layout.find('> div:nth-of-child(1)'); */
'<div>' +
' <p>Seleccione la imagen que desea procesar.</p>' +
' <input type="button" value="Seleccionar" class="btn btn-xlarge btn-success" />' +
' <span></span>' +
'</div>' +
/* Cargador - Progreso */
/* @this.layout.find('> div:nth-of-child(2)'); */
'<div>' +
' <div>' +
' <div></div>' +
' <div>' +
' <div></div>' +
' </div>' +
' </div>' +
'</div>' +
/* Editor */
/* @this.layout.find('> div:nth-of-child(3)');
* @sidebar = this.layout.find('> div:nth-of-child(3) > div > div > div:nth-of-type(1)');
* @body = this.layout.find('> div:nth-of-child(3) > div > div > div:nth-of-type(2) > div'); */
'<div>' +
' <div>' +
' <div>' +
' <div></div>' +
' <div>' +
' <div></div>' +
' </div>' +
' </div>' +
' </div>' +
'</div>'
);
}
}
sys.makeLayout('#div');
你可以这样做。。。
var string = 'This is\n' +
'a multiline\n' +
'string';
更新:
ECMAScript6(ES6)引入了一种新的文本类型,即模板文本。它们有很多特性,变量插值等等,但对于这个问题最重要的是,它们可以是多行的。
模板文本由反引号分隔:
var html = `
<div>
<span>Some HTML here</span>
</div>
`;
(注意:我并不主张在字符串中使用HTML)
浏览器支持是可以的,但您可以使用更兼容的转发器。
ES5原始答案:
Javascript没有here文档语法。但是,您可以转义字面换行符,这很接近:
"foo \
bar"