在es6模板文字,如何包装一个长模板文字到多行而不创建一个新的行在字符串?

例如,如果你这样做:

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

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


当前回答

这个NPM包允许你做以下事情…

import { oneLine } from 'common-tags';

const foo = oneLine`foo
bar
baz`;

console.log(foo); // foo bar baz

其他回答

这个NPM包允许你做以下事情…

import { oneLine } from 'common-tags';

const foo = oneLine`foo
bar
baz`;

console.log(foo); // foo bar baz

如果你的问题是相反的,你需要保留换行符,但由于某种原因,它们不被尊重,只需在文本容器中添加css属性:

#yourTextContainer {
  white-space: pre-line;
}

另一种选择是使用Array。像这样加入:

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

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

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`;