Is there a downside to using ES6 template literals syntax without a templated expression?

The most significant reason not to use them is that ES6 is not supported in all environments. Of course that might not affect you at all, but still: YAGNI. Don’t use template literals unless you need interpolation, multiline literals, or unescaped quotes and apostrophes. Much of the arguments from When to use double or single … Read more

Template literal inside of the RegEx

Your regex variable is a String. To make it a RegExp, use a RegExp constructor: const regex = new RegExp(String.raw`pattern_as_in_regex_literal_without_delimiters`) For example, a regex literal like /<\d+>/g can be re-written as const re = RegExp(String.raw`<\d+>`, ‘g’) // One \ is a literal backslash const re = RegExp(`<\\d+>`, ‘g’) // Two \ are required in a … Read more

Can ES6 template literals be substituted at runtime (or reused)?

To make these literals work like other template engines there needs to be an intermediary form. The best way to do this is to use the Function constructor. const templateString = “Hello ${this.name}!”; const templateVars = { name: “world” } const fillTemplate = function(templateString, templateVars){ return new Function(“return `”+templateString +”`;”).call(templateVars); } console.log(fillTemplate(templateString, templateVars)); As with … Read more

Template String As Object Property Name

Why are template strings not allowed as literal object keys? Template strings are expressions, not literals1. You can only use string literals (and identifiers) for property names, for everything else – that is not known to be static – you need a computed property name. Is it for performance reasons? No, that’s unlikely. It’s to … Read more

Defer execution for ES6 Template Literals

I can see three ways around this: Use template strings like they were designed to be used, without any format function: console.log(`Hello, ${“world”}. This is a ${“test”}`); // might make more sense with variables: var p0 = “world”, p1 = “test”; console.log(`Hello, ${p0}. This is a ${p1}`); or even function parameters for actual deferral of … Read more

Backticks (`…`) calling a function in JavaScript

It is called Tagged Template in ES-6 more could be read about them Here, funny I found the link in the starred section of the very chat. But the relevant part of the code is below (you can basically create a filtered sort). function tag(strings, …values) { assert(strings[0] === ‘a’); assert(strings[1] === ‘b’); assert(values[0] === … Read more

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

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 … Read more