我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
当前回答
更新:
ECMAScript6(ES6)引入了一种新的文本类型,即模板文本。它们有很多特性,变量插值等等,但对于这个问题最重要的是,它们可以是多行的。
模板文本由反引号分隔:
var html = `
<div>
<span>Some HTML here</span>
</div>
`;
(注意:我并不主张在字符串中使用HTML)
浏览器支持是可以的,但您可以使用更兼容的转发器。
ES5原始答案:
Javascript没有here文档语法。但是,您可以转义字面换行符,这很接近:
"foo \
bar"
其他回答
带变量的多行字符串
var x = 1
string = string + `<label class="container">
<p>${x}</p>
</label>`;
我认为这个解决方法应该适用于IE、Chrome、Firefox、Safari和Opera-
使用jQuery:
<xmp id="unique_id" style="display:none;">
Some plain text
Both type of quotes : " ' " And ' " '
JS Code : alert("Hello World");
HTML Code : <div class="some_class"></div>
</xmp>
<script>
alert($('#unique_id').html());
</script>
使用纯Javascript:
<xmp id="unique_id" style="display:none;">
Some plain text
Both type of quotes : " ' " And ' " '
JS Code : alert("Hello World");
HTML Code : <div class="some_class"></div>
</xmp>
<script>
alert(document.getElementById('unique_id').innerHTML);
</script>
干杯
我这样编程:
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');
我想我发现了另一种方法,可以在没有任何侵入性语法的情况下,在每一行中内联执行。使用Javascript将函数转换为字符串并使用/**/语法创建多行注释,然后删除“function(){/*\n”和“\n*/}”。
var multiline = function(string) { return string.toString().replace(/(^[^\n]*\n)|(\n\*\/\})/g, ""); };
console.log(multiline(function() {/*
Hello world!
I'm a multiline string!
Tada!
*/}));
我能看到的唯一缺陷是语法高亮显示。
编辑:如果我再向下滚动一点,我会看到这个答案完全一样:https://stackoverflow.com/a/5571069/916553
您可以使用标记的模板来确保获得所需的输出。
例如:
// 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'