我在 Ruby 中有以下代码。我想将此代码转换为 JavaScript。什么是 JS 中的等效代码?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
正如第一个回答提到的那样,使用 ES6 / Babel,你现在可以简单地使用反引号来创建多行字符串:
const htmlString = `Say hello to
multi-line
strings!`;
插值变量是一种流行的新功能,它带有反向划分的字符串:
const htmlString = `${user.name} liked your post about strings`;
这只是简化为串联:
user.name + ' liked your post about strings'
Google 的 JavaScript 样式指南建议使用字符串连接而不是转义换行符:
不要这样做:
var myString = 'A rather long string of English text, an error message \ actually that just keeps going and going -- an error \ message to make the Energizer bunny blush (right through \ those Schwarzenegger shades)! Where was I? Oh yes, \ you\'ve got an error and all the extraneous whitespace is \ just gravy. Have a nice day.';
在编译时无法安全地剥离每行开头的空格; 斜杠后的空格会导致棘手的错误; 虽然大多数脚本引擎支持这一点,但它不是 ECMAScript 的一部分。
请改用字符串连接:
var myString = 'A rather long string of English text, an error message ' + 'actually that just keeps going and going -- an error ' + 'message to make the Energizer bunny blush (right through ' + 'those Schwarzenegger shades)! Where was I? Oh yes, ' + 'you\'ve got an error and all the extraneous whitespace is ' + 'just gravy. Have a nice day.';
模式text = <<"HERE" This Is A Multiline String 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
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注意:在缩小 / 混淆代码后,这将丢失