在 es6 模板文字中,如何将长模板文字包装为多行而不在字符串中创建新行?
例如,如果您这样做:
const text = `a very long string that just continues
and continues and continues`
然后它将为字符串创建一个新的行符号,将其解释为有一个新行。如何在不创建换行符的情况下将长模板文字包装成多行?
在 es6 模板文字中,如何将长模板文字包装为多行而不在字符串中创建新行?
例如,如果您这样做:
const text = `a very long string that just continues
and continues and continues`
然后它将为字符串创建一个新的行符号,将其解释为有一个新行。如何在不创建换行符的情况下将长模板文字包装成多行?
如果在文本中的换行符处引入换行符( \
),则不会在输出上创建换行符:
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'));
另一种选择是使用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('')
编辑:我用这个实用程序制作了一个很小的 NPM module。它适用于网络和 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;
}
然后你可以标记任何你想要换行的模板文字:
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.`;
如果未来的开发人员不习惯标记模板语法或者如果您不使用描述性函数名称,这确实有可能出现意外行为的缺点,但它现在感觉是最干净的解决方案。