This tutorial explains about creating Multi line strings in ES6 and ES5, It also includes template literal syntax for writing a new way of the string enclosed in the backtick symbol. Template literals in ES6 support below features
- Interpolation
- Multi-Line String
- tagged Templates
- template literals(or template strins)
ES6 Template Literals
Template literals are a string with embedded expressions enclosed in backticks. Expressions are evaluated at runtime in JavaScript and replaced with the result.
It is also called String interpolation.
- Variable interpolation
For example lets define variable and print the variable
let name = "John";
console.log(`Hello ${name}`); // Hello John
- Interpolation with javascript expression
Javascript expressions are calculated and replaced in a string at runtime
const add = (first,second) => {
console.log(`The addition of ${first} and ${second} is ${first + second}`);
}
module.exports = {sum}
sum(10,20) # The addition of 10 and 20 is 30
ES6 tagged template example
template literals passed to an function
In the below example, declare an function that takes an string array and template literal interpolation
pass template literals string into an function.
let name = 'John';
let salary = 5000;
let result = print `I am ${ name } and my salary is ${ salary }`;
function print(strs, nameExpression, salaryExpression) {
console.log(strs[0]) // I am
console.log(strs[0]) // and my salary is
return strs[0] + nameExpression + strs[1] + salaryExpression;
}
console.log(result); // I am John and my salary is 5000
Another example is string.raw
is an tagged template function.
string.raw takes string and prints the raw string without escape character
let result = String.raw `Hello \n welcome \n This is paragraph.`
console.log(result); # Hello \n welcome \n This is paragraph.
How to create a multi-line string in ES6?
With ES6, you can create a multi line strings declare inside backticks(`) symbol, assigned to an string.
const multiLineString = `<div>
multi-line string
</div>`;
How to create a multi line string in ES5?
Before ES6, Strings declared in multiple lines using in two ways.
One way using escaping new line character
Declare an string with literal string enclosed in a single quotes.
Each line is end with backslash symbol with new line character
var multiLineString = 'Single line one \
Single line two \
Single line three \
Single line four';
Second way using append concatenate operator
Each line enclosed in backticks and append with +
operator.
var multiLineString = 'Single line one'+
' Single line two' +
' Single line three' +
' Single line four';
This is recommended way of declare an multi line string before ES6.