我在 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.';
网友回答:
ECMAScript 6 (ES6) 引入了一种新的文字类型,即模板文字。它们具有许多功能,可变插值等,但最重要的是,对于这个问题,它们可以是多行的。
模板文本由反引号分隔:
var html = `
<div>
<span>Some HTML here</span>
</div>
`;
(注意:我不提倡在字符串中使用 HTML)
浏览器支持是可以的,但您可以使用转译器来更兼容。
Javascript 没有 here-document 语法。但是,您可以转义文字换行符,它接近:
"foo
bar"
网友回答:
该模式在 js 中不可用(我记得在我过去的 Perl 时代经常使用它)。text = <<"HERE" This Is A Multiline String HERE
为了保持对复杂或长多行字符串的监督,我有时会使用数组模式:
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 注意:缩小/混淆代码后,这将丢失
模板简介:该模板名称为【简单地使用反引号创建多行字符串,JS中的等效代码是什么?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【JavaScript】栏目查找您需要的精美模板。