Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing string delimiters to backticks : possible impact?

ES6 introduced template strings delimited by backticks `.

In which cases would replacing single ' or double " quotes around a string by backticks yield a different result, or otherwise be unsafe ?

Escaping of existing backticks inside the code is performed as part of the operation.

// before
var message = "Display backtick ` on screen";

// after
var message = `Display backtick \` on screen`;

I understand that any string containing ${...} would fail as it would be (mis)interpreted as a placeholder. Are there any other relevant patterns ?


Context : this is for the development of a JS compression tool that automatically processes input code. The latter, and the strings it contains is user-provided, hence I have no control over its contents. The only assumption one can make is that it is valid Javascript.

Execution environment can by any recent browser or Node.js.

like image 237
Siorki Avatar asked Dec 05 '16 18:12

Siorki


People also ask

Are backticks slower than other strings in JavaScript?

The speed of string literals in JavaScript He said backtick literals are less performant (in other words, slower) because they need to processed. In other words, the variable interpolation that we want from backtick literals are an Achilles' heel — processing the template literals slows performance.

What do backticks do in JavaScript?

Backticks are an ES6 feature that allows you to create strings in JavaScript. Although backticks are mostly used for HTML or code embedding purposes, they also act similar to single and double quotes. Besides, using backticks makes it easier for string operations.

What is string interpolation in JavaScript?

String interpolation is a great programming language feature that allows injecting variables, function calls, arithmetic expressions directly into a string. String interpolation was absent in JavaScript before ES6.

What is ${} in HTML?

value INSIDE any string using the ${ } notation.


1 Answers

You can check the grammar of string literals and no-substitution-templates.
Apart from the ` vs. ' vs. " and the special meaning of ${ that you already mentioned, only line breaks differ between the two forms. We can ignore line continuations ("escaped linebreaks") as your minifier would strip them away anyway, but plain line breaks are valid inside templates while not inside string literals, so if you convert back and forth you'll have to care about those as well. You can even use them to save another byte if your string literal contains \n.

like image 80
Bergi Avatar answered Oct 04 '22 12:10

Bergi