ES6: Template Literals

Template literals is the new feature introduce in ES6. Previously string manipulation was very restricted. Was not able to parse variables in sting, had to concatenate. Same for multi line string.

In ES6 template string introduce by using back-ticks(` `) instead of single or double quotes for strings. A template string could  be written as :

Synatax

`Hello World!!`
var msg = `Hello Word!!`

 

Multiline String

For multiline string we need to use ‘\n’ for line break but in template literals string in next line will automatically treated as new line.

Syntax for multiline string

console.log("Hi Jon Doe.\n"+
"How are you?");
//"Hi Jon Doe.
//How are you?"

 

Syntax for same multiline string using template literals

console.log(`Hi Jon Doe.
How are you?`);
//"Hi Jon Doe.
//How are you?"

 

String Substitution

One of the best feature of templating, allows any valid javascript expression in template.

Syntax we use

var person = {name:'Jon Doe', age:42, sex:'Male'};
console.log(person.name +' is a '+person.age+' years old '+person.sex);
"Jon Doe is a 42 years old Male"

Syntax use string substitution

var person = {name:'Jon Doe', age:42, sex:'Male'};
console.log(`${person.name } is a ${person.age} years old ${person.sex}`);
"Jon Doe is a 42 years old Male"

Few more examples

var a = 10;
var b = 10;

console.log(`${a} + ${b} = ${a + b}`); // 10 + 10 = 20
console.log(`${a} * ${b} = ${a * b}`); // 10 * 10 = 100
console.log(`${a} ^ ${b} = ${Math.pow(a , b)}`); // 10 ^ 10 = 10000000000

 

var person = {name:'Jon Doe', age:42, sex:'Male'};

function salutation(sex){
  return (sex == 'Male') ? 'Mr.' : 'Miss.';
}

console.log(`Hello ${salutation(person.sex)} ${person.name}`);
//Hello Mr. Jon Doe

console.log(`Hello ${salutation(person.sex)} ${person.name.toUpperCase()}`);
//Hello Mr. JON DOE

 

Tagged template literals

Tagged template literals helps us to modify the output of a template literals using a function. The first argument contains an array of string literals . The second, and each argument after the first one, are the values of the processed substitution expressions . In the end,  function returns processed string.

How we write it

getUrl([ "http://example.com/product?category=", "&id="],category, id);

How it be

getUrl`http://example.com/product?category=${category}&id=${id}`;

 

Lets see it in details

var category = 'demo', id = 201;
function getUrl(strings, val1, val2){
    return strings[0]+val1+strings[1]+val2;
}
getUrl([ "http://example.com/product?category=", "&id="],category, id);
"http://example.com/product?category=demo&id=201"

ES6 approach

var category = 'demo', id = 201;
function getUrl(strings, ...values){
    return strings[0]+values[0]+strings[1]+values[1];
}
getUrl`http://example.com/product?category=${category}&id=${id}`;
"http://example.com/product?category=demo&id=201"