Search notes:

JavaScript: template literals

A template literal is a string that is quoted with backslashes.

Multi line strings

Template literals allow to create multi line strings:
let multilineString = `This is a
multi line string.
A multi line string is started
and ended with backslashes.`;

console.log(multilineString);
Github repository about-javascript, path: /expressions/primary-expressions/template-literals/multi-line-string.js

Multi line strings without template literals

In earlier times, it was possible to store multi line strings in comments within a function and then extract them from the function body:
function hereDoc(text) { // http://stackoverflow.com/a/5571069/180275
  return text.toString().
      replace(/^[^\/]+\/\*!?/, '').
      replace(/\*\/[^\/]+$/, '');
}

multilineString = hereDoc(function() {/*!        1st line

    3rd line

    5th line

    7ht line*/}
);

console.log(multilineString);
Github repository about-javascript, path: /expressions/primary-expressions/template-literals/here-doc.js

Placeholders

A template literal can contain placeholders (${…}) whose expression is evaluated and embedded where they occur.
function twice(num) {
  return num*2;
}

let num=42;
let greeting='Hello'

let expandedString = `${greeting}, the number is ${num}, twice the number is ${twice(num)}`;
console.log(expandedString);
Github repository about-javascript, path: /expressions/primary-expressions/template-literals/placeholders.js

Index