我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
当前回答
有这样一个图书馆,它很漂亮:
https://github.com/sindresorhus/multiline
之前
var str = '' +
'<!doctype html>' +
'<html>' +
' <body>' +
' <h1>❤ unicorns</h1>' +
' </body>' +
'</html>' +
'';
之后
var str = multiline(function(){/*
<!doctype html>
<html>
<body>
<h1>❤ unicorns</h1>
</body>
</html>
*/});
其他回答
模式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注意:缩小/模糊代码后,这将丢失
我通过输出一个div,使其隐藏,并在需要时通过jQuery调用div id来解决这个问题。
e.g.
<div id="UniqueID" style="display:none;">
Strings
On
Multiple
Lines
Here
</div>
然后,当我需要获取字符串时,我只需使用以下jQuery:
$('#UniqueID').html();
它会在多行上返回我的文本。如果我打电话
alert($('#UniqueID').html());
我得到:
准确的
Ruby produce:“This\nIs\nMultiline\nString\n”-在JS下面生成完全相同的字符串
text=`此是A.多行一串`//测试console.log(JSON.stringify(文本));console.log(文本);
这是对朗尼最佳答案的改进,因为他的答案中的换行符与ruby输出中的位置不完全相同
您可以使用标记的模板来确保获得所需的输出。
例如:
// 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'
更新:
ECMAScript6(ES6)引入了一种新的文本类型,即模板文本。它们有很多特性,变量插值等等,但对于这个问题最重要的是,它们可以是多行的。
模板文本由反引号分隔:
var html = `
<div>
<span>Some HTML here</span>
</div>
`;
(注意:我并不主张在字符串中使用HTML)
浏览器支持是可以的,但您可以使用更兼容的转发器。
ES5原始答案:
Javascript没有here文档语法。但是,您可以转义字面换行符,这很接近:
"foo \
bar"