Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape dollar sign in JavaScript template literals (template strings)

Tags:

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

like image 930
Scott Selby Avatar asked Jun 26 '16 22:06

Scott Selby


People also ask

What does ${} In JavaScript mean?

${} is a placeholder that is used in template literals. You can use any valid JavaScript expression such as variable, arithmetic operation, function call, and others inside ${}. The expression used inside ${} is executed at runtime, and its output is passed as a string to template literals.

What is ${} in HTML?

The ${} syntax allows us to put an expression in it and it will produce the value, which in our case above is just a variable that holds a string! There is something to note here: if you wanted to add in values, like above, you do not need to use a Template Literal for the name variable.

Are template literals strings?

Template literals are string literals allowing embedded expressions using backtick characters (`). You can use multi-line strings and string interpolation features with them. Formerly known as template strings.


1 Answers

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}` 
like image 132
Bergi Avatar answered Sep 24 '22 16:09

Bergi