将长模板文字行包装为多行而不在字符串中创建新行

IT技术 javascript ecmascript-6 template-literals
2021-02-20 12:11:26

在 es6 模板文字中,如何将长模板文字包装为多行而不在字符串中创建新行?

例如,如果您这样做:

const text = `a very long string that just continues
and continues and continues`

然后它将为字符串创建一个新的行符号,将其解释为有一个新行。如何在不创建换行符的情况下将长模板文字包装成多行?

6个回答

如果在文本中的换行符处引入换行符( \),则不会在输出上创建换行符:

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
在我的情况下并不容易,因为不同的变量是从 coffeescript 配置文件等中获取的。mm .. 似乎它可以正常工作但由于某种原因它在那里添加了空白空间
2021-04-17 12:11:26
如果您在第一行使用连续行,它对我不起作用(节点 v7)
2021-04-24 12:11:26
不确定我明白你的意思。你能提供一个REPL 示例吗?
2021-05-03 12:11:26
此解决方案不适用于缩进(并且缩进在开发中很常见)。新行中 \ 之后的字符必须是该行的第一个字符意思是,and continues...必须从新行的第 0 个位置开始,打破缩进规则。
2021-05-05 12:11:26
如果您在测试中使用它,有时它不会返回相同的字符串。我已经使用deline解决了我的头痛问题,这只是一个1.1k Airbnb library
2021-05-16 12:11:26

这是一个旧的。但它出现了。如果您在编辑器中留下任何空格,它将把它们放在那里。

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`;
对于较新的 JavaScript 引擎,连接也慢得多。请参阅此 StackOverflow 帖子上的“更新(2020 年 2 月)”部分
2021-04-24 12:11:26
不幸的是,这不适用于标记模板文字。
2021-05-08 12:11:26
很好,但我使用它的部分原因是为了避免使用“+”符号。它使代码更难阅读,也更烦人。
2021-05-15 12:11:26

您可以只吃模板文字中的换行符。

// 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'));

这是一个非常好的 hack,但是如果您prettier在 IDE 中配置了一个漂亮的格式化程序(如,它就会失败prettier将其包装回单行。
2021-05-09 12:11:26

另一种选择是使用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('')
好优雅!谢谢!
2021-05-15 12:11:26

编辑:我用这个实用程序制作了一个很小的 ​​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.`;

如果未来的开发人员不习惯标记模板语法或者如果您不使用描述性函数名称,这确实有可能出现意外行为的缺点,但它现在感觉是最干净的解决方案。