简体   繁体   中英

Escape dollar sign in JavaScript template literals (template strings)

I am using the new template literals (template strings) syntax of JavaScript ES6 Docs Here and I am not quite sure how to escape the dollar sign that is used to break the string to add a parameter.

Here is what I am trying to do:

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

that works fine... but I would really prefer to not have that space $ ${title}

that leaves the end result looking like :

... in the amount of $ 25.99 for the purchase...

I would really rather prefer

... in the amount of $25.99 for the purchase ...

I guess that is ok, or obviously I could use the old way that still works, but it would be nice to know how to fix this. I linked to the Mozilla docs , and I can't find anything in there about it, hopefully someone has an idea how to fix this

The only case where $ does not produce the literal $ is before a { , otherwise you do not need to escape it.

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

does work therefore. In case you need to escape anything, the backslash \\ is the escape character in template strings as well, so (while unnecessary) the following works as well:

var response = `You have \$${money}`
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.`

在美元符号前面加一个反斜杠是我想到的第一件事,它有效:

\${DEPLOYMENT_NAME}

这对我有用。

var response = `You have \$\{money}`;
<v-btn :href="mail">
   Send Mail
</v-btn>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM