With the exciting beta release of ECMAScript 6, we thought it would be fun to play with one of its boasted features and provide a little tutorial. Template strings are strings that allow for embedded expressions.
With the exciting beta release of ECMAScript 6, we thought it would be fun to play with one of its boasted features and provide a little tutorial. Template strings are strings that allow for embedded expressions.
The Template Strings feature brings a lot of goodies to JavaScript strings and also helps us to eliminate extra libraries. It is supported by Chrome 41+, IE Tech Preview, Firefoz 35+ and also io.js. Most of the major ES6 transpilers also support this feature letting us start to use it in production immediately.
For template strings, we use the back-tick (` `) character instead of the regular single or double quotes.
Multiline String
Normally, we would use one of the following syntax to create a multiline string:
var string1 = 'This is line 1\n\
This is line 2';
// or
var string2 = 'This is line 1\n' +
'This is line 2'
Now, with template strings, any new line character in source code is treated as an actual new line character. The code can be written as:
var string1 = `This is line 1
This is line 2`;
Variable Substitution
Using template strings, we can not substiute variables on the runtime. To use this feature, wrap the variable name inside ${} in the string template:
var a = 10,
string=`Value of a is ${a}`;
console.log(string);// Value of a is 10
This can also be used for expressions:
var a = 10,
string = `a times 10 is ${a*10}`;
console.log(string);
// a times 10 is 100
function sum (a, b) {
return a + b;
}
var string2 = `10 + 20 = ${sum(10, 20)}`;
console.log(string2);
// 10 + 20 = 30
Tagged Templates
Tag is a function that has the ability to intercept and process templates. Tag is a function which gets the individual string fragments in a template as the first argument and variables as other arguments:
function tagFn (strings, ...value) {
console.log(strings[0]); // "10 + 20 = "
console.log(values[0]); // 10
console.log(values[1]); // 20
return `something else`;
}
var a = 10,
b = 20;
tagFn` 10 * 20 = ${a+b}`
// something else
This is a pretty powerful feature and can be used for purposes like sanitization of HTML, i18n or something similar.
Written by Mayank Patel