Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ECMAScript template literals like 'some ${string}' are not working

I wanted to try using template literals and it’s not working: it’s displaying the literal variable names, instead of the values. I am using Chrome v50.0.2 (and jQuery).

Example

console.log('categoryName: ${this.categoryName}\ncategoryElements: ${this.categoryElements} '); 

Output

${this.categoryName} categoryElements: ${this.categoryElements} 
like image 524
Ron I Avatar asked May 16 '16 02:05

Ron I


People also ask

Why template literal is not working?

If you are using JavaScript's new template literal syntax in a JSP page it might not work as expected. That's because JSP and JavaScript both use the ${myVar} syntax.

Do template strings support multiline strings?

Template Strings significantly simplify multiline strings. Simply include newlines where they are needed and BOOM. Here's an example: Any whitespace inside of the backtick syntax will also be considered part of the string.

How do you declare a JavaScript expression inside a template literal?

Description. Template literals are enclosed by backtick (`) characters instead of double or single quotes. Along with having normal strings, template literals can also contain other parts called placeholders, which are embedded expressions delimited by a dollar sign and curly braces: ${expression} .

What is ES6 template string?

Template literals are a new feature introduced in ECMAScript 2015/ ES6. It provides an easy way to create multiline strings and perform string interpolation. Template literals are the string literals and allow embedded expressions.


1 Answers

JavaScript template literals require backticks, not straight quotation marks.

You need to use backticks (otherwise known as "grave accents" - which you'll find next to the 1 key if you're using a QWERTY keyboard) - rather than single quotes - to create a template literal.

Backticks are common in many programming languages but may be new to JavaScript developers.

Example:
categoryName="name"; categoryElements="element"; console.log(`categoryName: ${this.categoryName}\ncategoryElements: ${categoryElements} `)  
Output:
VM626:1 categoryName: name  categoryElements: element 
See:

Usage of the backtick character (`) in JavaScript

like image 125
Tim Grant Avatar answered Sep 22 '22 14:09

Tim Grant