ES6
comes up with a new type of string literal, using the `
back-tick as the delimiter. These literals do allow basic string interpolation expressions to be embedded, which are then automatically parsed and evaluated.
let actor = {name: 'RajiniKanth', age: 68};
let oldWayStr = "<p>My name is " + actor.name + ",</p>\n" +
"<p>I am " + actor.age + " old</p>\n";
let newWayHtmlStr =
`<p>My name is ${actor.name},</p>
<p>I am ${actor.age} old</p>`;
console.log(oldWayStr);
console.log(newWayHtmlStr);
As you can see, we used the ..`` around a series of characters, which are interpreted as a string literal, but any expressions of the form ${..}
are parsed and evaluated inline immediately.
One really nice benefit of interpolated string literals is they are allowed to split across multiple lines:
var Actor = {"name" : "RajiniKanth"};
var text =
`Now is the time for all good men like ${Actor.name}
to come to the aid of their
country!`;
console.log( text );
Interpolated Expressions
Any valid expression is allowed to appear inside ${..}
in an interpolated string lit‐ eral
, including function calls, inline function expression calls, and even other interpo‐ lated string literals
!
function upper(s) {
return s.toUpperCase();
}
var who = "reader"
var text =
`A very ${upper( "warm" )} welcome
to all of you ${upper( `${who}s` )}!`;
console.log( text );
Here, the inner ${who}s`` interpolated string literal was a little bit nicer convenience for us when combining the who variable with the "s"
string, as opposed to who + "s". Also to keep an note is an interpolated string literal is just lexically scoped
where it appears, not dynamically scoped
in any way
function foo(str) {
var name = "foo";
console.log( str );
}
function bar() {
var name = "bar";
foo( `Hello from ${name}!` );
}
var name = "global";
bar();
Using the template literal
for the HTML is definitely more readable by reducing the annoyance.
The plain old way:
'<div class="' + className + '">' +
'<p>' + content + '</p>' +
'<a href="' + link + '">Let\'s go</a>'
'</div>';
With ES6
:
`<div class="${className}">
<p>${content}</p>
<a href="${link}">Let's go</a>
</div>`
- Your string can span multiple lines.
- You don't have to escape quotation characters.
- You can avoid groupings like: '">'
- You don't have to use the plus operator.
Tagged Template Literals
We can also tag a template
string, when a template
string is tagged, the literals
and substitutions are passed to function which returns the resulting value.
function myTaggedLiteral(strings) {
console.log(strings);
}
myTaggedLiteral`test`;
function myTaggedLiteral(strings,value,value2) {
console.log(strings,value, value2);
}
let someText = 'Neat';
myTaggedLiteral`test ${someText} ${2 + 3}`;
We can use the spread
operator here to pass multiple values. The first argument — we called it strings — is an array of all the plain strings (the stuff between any interpolated expressions).
we then gather up all subsequent arguments into an array called values using the ... gather/rest operator
, though you could of course have left them as individual named parameters following the strings parameter like we did above (value1, value2 etc)
.
function myTaggedLiteral(strings,...values) {
console.log(strings);
console.log(values);
}
let someText = 'Neat';
myTaggedLiteral`test ${someText} ${2 + 3}`;
The argument(s)
gathered into our values array are the results of the already evaluated interpolation expressions found in the string literal. A tagged string literal
is like a processing step after the interpolations are evaluated but before the final string value is compiled, allowing you more control over generating the string from the literal. Let's look at an example of creating a re-usable templates
.
const Actor = {
name: "RajiniKanth",
store: "Landmark"
}
const ActorTemplate = templater`<article>
<h3>${'name'} is a Actor</h3>
<p>You can find his movies at ${'store'}.</p>
</article>`;
function templater(strings, ...keys) {
return function(data) {
let temp = strings.slice();
keys.forEach((key, i) => {
temp[i] = temp[i] + data[key];
});
return temp.join('');
}
};
const myTemplate = ActorTemplate(Actor);
console.log(myTemplate);
Raw Strings
our tag functions receive a first argument we called strings
, which is an array
. But there’s an additional bit of data included: the raw unprocessed versions of all the strings. You can access those raw string values using the .raw
property, like this:
function showraw(strings, ...values) {
console.log( strings );
console.log( strings.raw );
}
showraw`Hello\nWorld`;
As you can see, the raw
version of the string preserves the escaped \n sequence, while the processed version of the string treats it like an unescaped real new-line. ES6
comes with a built-in function that can be used as a string literal tag: String.raw(..)
. It simply passes through the raw versions of the strings
:
console.log( `Hello\nWorld` );
console.log( String.raw`Hello\nWorld` );