且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

es6多行模板字符串,不带新行并允许缩进

更新时间:2022-05-15 07:27:42

这个问题的两个答案,但只有一个可能被认为是***的。

Two answers for this problem, but only one may be considered optimal.

在模板文字内部,javascript可以在表达式内使用,如 $ {} 。因此它可能具有缩进的多行模板文字,如下所示。注意事项是一些有效的js字符或值必须存在于表达式中,例如空字符串或变量。

Inside template literals, javascript can be used inside of expressions like ${}. Its therefore possible to have indented multiline template literals such as the following. The caveat is some valid js character or value must be present in the expression, such as an empty string or variable.

const templateLiteral = `abcdefgh${''
  }ijklmnopqrst${''
  }uvwxyz`;

// "abcdefghijklmnopqrstuvwxyz"

此方法使您的代码看起来像垃圾。不推荐。

This method makes your code look like crap. Not recommended.

第二种方法是由@SzybkiSasza推荐的,似乎是***的选择。由于某种原因,我并没有发生连接模板文字。我是derp。

The second method was recommended by @SzybkiSasza and seems to be the best option available. For some reason concatenating template literals didn't occur to me as possible. I'm derp.

const templateLiteral = `abcdefgh` +
  `ijklmnopqrst` +
  `uvwxyz`;

// "abcdefghijklmnopqrstuvwxyz"