Template Literals
Template literals are string literals allow embedded expressions.
Here, we can use multi-line strings and string Interpolation features with them.
We use backtick (` `) to enclosed string instead of single quote or double quotes.
Example with use of Template Literals:-
var str = `string data`; //single line
console.log (`string line 1
string line 2`);//multiline
`string data ${expression} string data`// String interpolation
tag `string data ${expression} string data`//Tagged templates
String Interpolation
The syntax is:-
${}
Example 1:-
let one = Hello;
let two = 'Navneet';
console.log(`ohhh, ${one}
How are you ${two}`);
Example 2:-
let a = 100;
let b = 200;
console.log(`The sum of the variables ${a} and ${b} is:
${a+b}.`);
Tagged templates
Tagged templates is a function allow us to parse template literals with a function.
The first argument of a tag function contains an array of string values.
The remaining arguments are related to the expressions.
Example 1:-
function Test(data, a1, a2)
{
console.log(data);
console.log(a1+" and "+a2);
}
let str = 'ohhhhh';
Test`superb ,aman ${str} ${100+200}`;
Example 2:-
function test(firstName, lastName)
{
return `Good morning ${firstName} ${lastName}!
How are you?`
}
console.log(test('Heera', 'Babu'))
Raw Strings
The String.raw() method is a tag function of template literals.
Synatx is:-
String.raw`template string`
Example 1:-
let data = String.raw`ohhhh, hiiiii \n superb yaar `
console.log(data)