Introduced in ES2015 edition of the ECMAScript specification (ES6) Template Literals(or the old name for template literals: Template strings) offer a new way of making strings in JavaScript that add a lot of powerful new capabilities, such as using placeholders to embed expressions in a string and generating multiline strings more easily.

The syntax is straightforward, just use _backticks _instead of double or single quotes:

const literal = `hello!`

They provide several features that regular strings built with quotes do not, in particular:

  • They provide a simple way to include variables and expressions in strings.
  • Template literals give a great syntax to define multiline strings.
  • They allow creating DSLs using template tags.
  • It is more straightforward to format a string because the format remains as we wrote it.

Index:

  • Declaring Strings
  • Multiple lines with interpolate expressions
  • Tagged Templates
  • Shell commands
  • Embedded HTML
  • Raw String
  • Customizable regexp

Let’s see some useful examples.

Declaring Strings

In JavaScript, you can write a string using single quotes (‘ ‘):

const single = 'Hello'

Or using double quotes (“ “):

const double = "Hello"

There is no significant difference in JavaScript between single- or double-quoted strings.

Now, if you want to include an expression you can do:

let name= "Kesk";

const hello = "Hello" + name + "!";
console.log(hello);
//Hello Kesk

But it gets complicated if you want to format a text or you have multiples expressions inside it:

To achieve this:

//Hello Kesk!
  //.This is a multiline message
    //that maintains the format

We can do:

const name = "Kesk"

const s1 = "Hello " + name + "! \n"
+   ".This is a multiline message \n"
+      "that maintains the format \n";
console.log(s1);

Result in chrome dev tools.

#javascript-tips #web-development #javascript #programming

Different uses for Template Literals in JavaScript
10.15 GEEK