在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

其他回答

如果你在字面值的换行符处引入了一个续行符(\),它不会在输出时创建换行符:

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

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

[
    'This is a very long string. ',
    'It just keeps going ',
    'and going ',
    'and going ',
    'and going ',
    'and going ',
    'and going ',
    'and going',
].join('')

类似于Doug的回答,这被我的TSLint配置所接受,并且不受我的IntelliJ自动格式化器的影响:

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

只要用普通的+符号

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

你可以直接吃掉模板文字中的换行符。

//感谢https://twitter.com/awbjs给我介绍这个想法 //这里:https://esdiscuss.org/topic/multiline-template-strings-that-don-t-break-indentation const printLongLine = continue => { Const text = '一个很长的字符串,只有${continues}${" }和${continuations}和${continuations} '; 返回文本; } console.log (printLongLine('继续'));