使用模板文字在javascript中构建多行字符串

时间:2017-08-30 21:10:16

标签: javascript multiline template-literals

我正在尝试使用模板文字构建一个包含多个查询参数的网址。

为了便于阅读,我将每个查询参数放在一个单独的行上。它看起来像下面的例子,只有更长的时间。

const url = `http://example.com/hey?
one=${one}&
two=${two}&
three=${three}`;

我的问题涉及制作一个多行文字字符串,其中包含每个参数之间没有换行符(\ n)的最终值。这是可能的模板文字,还是我应该用旧的方式连接字符串?

1 个答案:

答案 0 :(得分:4)

您可以在行尾使用反斜杠作为模板文字,使用更多行,但没有换行符。

const 
    one = 'eins', two = 'zwei', three = 'drei',
    url = `http://example.com/hey?\
one=${one}&\
two=${two}&\
three=${three}`;

console.log(url);