在es6模板文字中,如何将长模板文字包装成多行而不在字符串中创建新行?
例如,如果您这样做:
const text = `a very long string that just continues
and continues and continues`
然后,它将为字符串创建一个新行符号,因为它将解释为具有新行。如何在不创建换行符的情况下将长模板文字包装到多行?
如果在文字中的换行符处引入line continuation(\
),它将不会在输出中创建换行符:
const text = `a very long string that just continues\
and continues and continues`;
console.log(text); // a very long string that just continuesand continues and continues
这是旧的。但它来了。如果您在编辑器中留有任何空格,它将放置在其中。
if
const text = `a very long string that just continues\
and continues and continues`;
只做普通的+符号
if
const text = `a very long string that just continues` +
`and continues and continues`;
您可以只吃模板文字中的换行符。
// Thanks to https://twitter.com/awbjs for introducing me to the idea
// here: https://esdiscuss.org/topic/multiline-template-strings-that-don-t-break-indentation
const printLongLine = continues => {
const text = `a very long string that just ${continues}${''
} and ${continues} and ${continues}`;
return text;
}
console.log(printLongLine('continues'));
EDIT:我使用此实用程序制作了一个很小的NPM模块。它可以在Web和Node上运行,我强烈建议在下面的答案中使用它,因为它的功能更强大。如果您手动将换行符输入为\n
,它还可以保留结果中的换行符,并提供了一些功能,用于当您已经将模板文字标签用于其他内容时:https://github.com/iansan5653/compress-tag
我知道我在这里回答晚了,但是被接受的答案仍然具有在换行符后不允许缩进的缺点,这意味着您仍然不能仅通过转义换行符来编写外观精美的代码。
相反,为什么不使用tagged template literal function?
function noWhiteSpace(strings, ...placeholders) {
// Build the string as normal, combining all the strings and placeholders:
let withSpace = strings.reduce((result, string, i) => (result + placeholders[i - 1] + string));
let withoutSpace = withSpace.replace(/\s\s+/g, ' ');
return withoutSpace;
}
然后,您可以只标记要在其中使用换行符的任何模板文字:
let myString = noWhiteSpace`This is a really long string, that needs to wrap over
several lines. With a normal template literal you can't do that, but you can
use a template literal tag to allow line breaks and indents.`;
如果确实不适合将来的开发人员使用带标签的模板语法,或者您不使用描述性的函数名称,那么这样做确实可能会出现意外行为,但这似乎是目前最干净的解决方案。
另一个选择是使用Array.join
,如下所示:
[
'This is a very long string. ',
'It just keeps going ',
'and going ',
'and going ',
'and going ',
'and going ',
'and going ',
'and going',
].join('')
使用旧的和新的。模板文字很好,但是如果您要避免使用冗长的文字以使代码行紧凑,请将它们串联起来,ESLint不会引起大惊小怪。
const text = `a very long string that just continues`
+` and continues and continues`;
console.log(text);
类似于Doug's answer,这被我的TSLint配置接受,而我的IntelliJ自动格式化程序则保持不变:
const text = `a very long string that just ${
continues
} and ${continues} and ${continues}`
@ CodingIntrigue提出的解决方案在节点7上对我不起作用。嗯,如果我在第一行上不使用行延续,它就可以工作,否则失败。
这可能不是最好的解决方案,但是它可以正常工作:
(`
border:1px solid blue;
border-radius:10px;
padding: 14px 25px;
text-decoration:none;
display: inline-block;
text-align: center;`).replace(/\n/g,'').trim();