逃避美元符号es6字符串文字

时间:2016-06-26 22:13:07

标签: javascript ecmascript-6

我正在使用javascript es6 Docs Here的新字符串文字语法,我不太清楚如何转义用于打破字符串以添加参数的美元符号。这是我想要做的:

var response = `I consent to my credit card being charged in the amount of
                 $ ${ total } for the purchase of ${ item.title } and any
                 applicable sales tax.`

效果很好......但我真的更愿意没有那个空间$ ${title}

使最终结果看起来像:

  

......购买金额为25.99美元......

我真的更喜欢

  

......购买金额为25.99美元......

我想这没关系,或者显然我可以使用仍旧有效的旧方式,但知道如何解决这个问题会很好。我链接到Mozilla文档,我无法在其中找到任何内容,希望有人知道如何解决这个问题

4 个答案:

答案 0 :(得分:16)

$不生成文字$的唯一情况是在{之前,否则您无需转义它。

var response = `You have $${money}`

确实有效。如果您需要转义任何内容,反斜杠\也是模板字符串中的转义字符,因此(虽然不必要)以下内容也适用:

var response = `You have \$${money}`

答案 1 :(得分:11)

var response = `I consent to my credit card being charged in the amount of
                 $${ total } for the purchase of ${ item.title } and any
                 applicable sales tax.`

答案 2 :(得分:3)

在美元符号前面加上一个反斜杠是我想到的第一件事,它起作用了:

\${DEPLOYMENT_NAME}

答案 3 :(得分:0)

这适合我。

var response = `You have \$\{money}`;