7

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.

Siorki
  • 183
  • 8
  • What about something like this: var message = "Hello, I'm Mike, it's nice to meet you". Would that come out as \`Hello, I\`m Mike, it\`s nice to meet you\`? – Sari Rahal Dec 05 '16 at 19:11
  • @SariRahal The OP asked about replacing quotes *around* a string. – Michał Perłakowski Dec 05 '16 at 19:18
  • 3
    Might I suggest that you use a parser for processing code, instead of thinking about doing it with search-and-replace? http://esprima.org/ should have all the features you need. – Tomalak Dec 05 '16 at 19:29
  • @Siorki, take a look at [Tagged template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals) and especially on the [Raw Strings](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Raw_strings) feature. That are significant differences to single or double quotes. – Thomas Dec 05 '16 at 19:49
  • @Thomas, these - along with expression interpolation - are the reason I only intend to replace `'` or `"` with ` , not the other way around. There are too many new features with template literals that plain old quotes do no support. – Siorki Dec 05 '16 at 21:22

1 Answers1

2

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375