Vil*_*oja 114 javascript ecmascript-6 template-literals
在es6模板文字中,如何在不在字符串中创建新行的情况下将长模板文字包装到多行?
例如,如果您这样做:
const text = `a very long string that just continues
and continues and continues`
Run Code Online (Sandbox Code Playgroud)
然后它将为字符串创建一个新的行符号,将其解释为具有新行.如何在不创建换行符的情况下将长模板文字包装到多行?
Cod*_*gue 149
如果在文字中的换行符处引入行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
Run Code Online (Sandbox Code Playgroud)
小智 44
这是一个旧的.但它出现了.如果你在编辑器中留下任何空格,它会把它们放在那里.
if
const text = `a very long string that just continues\
and continues and continues`;
Run Code Online (Sandbox Code Playgroud)
只需做正常的+符号
if
const text = `a very long string that just continues` +
`and continues and continues`;
Run Code Online (Sandbox Code Playgroud)
Dou*_*urn 18
你可以只吃模板文字中的换行符.
// 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'));
Run Code Online (Sandbox Code Playgroud)
Lir*_*n H 14
另一种选择是使用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('')
Run Code Online (Sandbox Code Playgroud)
Ian*_*Ian 11
编辑:我已经使用此实用程序制作了一个很小的NPM模块。它可以在Web和Node上运行,我强烈建议在下面的答案中使用它,因为它的功能更强大。如果您手动将换行符输入为\n
,它还允许在结果中保留换行符,并为您已经将模板文字标签用于其他用途提供功能:https : //github.com/iansan5653/compress-tag
我知道我在这里迟到了答案,但是被接受的答案仍然具有在换行符后不允许缩进的缺点,这意味着您仍然不能仅通过转义换行符来编写看起来很漂亮的代码。
相反,为什么不使用带标签的模板文字函数呢?
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;
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以标记要在其中使用换行符的任何模板文字:
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.`;
Run Code Online (Sandbox Code Playgroud)
如果将来的开发人员不习惯使用标记的模板语法,或者如果您不使用描述性的函数名称,那么这样做确实可能会出现意外行为,但感觉这是目前最干净的解决方案。
使用旧的和新的。模板字面量很好,但如果你想避免冗长的字面量以拥有紧凑的代码行,请将它们连接起来,ESLint 不会引起大惊小怪。
const text = `a very long string that just continues`
+` and continues and continues`;
console.log(text);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
33299 次 |
最近记录: |