ES6 – Template string (back ticks)

Hi, in this post we are going to know how “template string” works in Js.

Template string is just another way to declare string but in a very easy way.

Template string have new features as embedded expressions, multi-line strings, string interpolation , string tagging, string formatting and more.

To write a string with template string we use back ticks instead of double quotes:

const doubleQuotesString = "Cristina Elizabeth Rojas Zamora";

const templateString = `Cristina Elizabeth Rojas Zamora`;

console.log(doubleQuotesString === templateString);

Result:

Now I’m going to show you different ways where you can implement template strings:

Handling expressions inside strings

To handle expressions inside our string we need to place the expression adding the dollar sign at the beginning then put your expression inside curly brackets

${expression}

Example:

let one = 1;
let thirty = 30;
const year = 1989;

const cristinaAge = `I'm Cristina Rojas and my age is ${one + thirty} born in ${year}`;

console.log(cristinaAge)

Result:

Work with multiple strings

If we need to work with multiple strings in ES5 we need to use \n to add new line breaks:

const multiline = "I'm\nCristina\nRojas"; // ES5

console.log(multiline);

Result:

With ES6 we do the same like this:

const multiline = 
`I'm
Cristina 
Rojas`;

console.log(multiline);

Result:

Raw string

A raw string is a normal string in which escaped characters aren’t interpreted.

const one = 1;
const thirty = 30;

const rawString = String.raw`I'm\n${one + thirty} Years old`;

console.log(rawString);

Result:

By Cristina Rojas.