loading...

Template Strings

mohananagavenkat profile image Mohana Naga Venkat Sayempu ・2 min read

ES6 template strings, denoted by backticks rather than single or double quotes, enable multiline strings, expression substitution, and tagged templates.

Multiline

All whitespace characters in backtick template strings are preserved, so no extra formatting is required for multiline strings.

var address = `29 Acacia Road,
Nuttytown,
England`;

Expression Substitution

Template strings are able to evaluate any expression against values in their current scope using ${} syntax.

⚠️ Be careful when building strings in this way from user input since you may introduce injection vulnerabilities, see tagged templates below for an alternative approach.

var name = 'Billy';
var born = 1992;
var now = () => new Date().getFullYear();

var message = `${name} is ${now()-born} years old`;
// 'Billy is 23 years old'

Tagged Templates

Tagged templates provide an abstracted and safer approach to string concatenation with dynamic values. They work by providing a layer of syntactic sugar over the process of implementing template generating functions. These functions are referred to as "template tags".

By using the func`some string`; syntax we invoke a template tag, that is a function to be run in order to process a template string. The template tag function receives the plain string parts and evaluated expressions in separate ordered arrays to be combined in a controlled manner, rather than blindly concatenated.

Template tags could be used by libraries to variously escape user input, strip tags, perform internationalization or provide any other string-based functionality via an arbitrary DSL.

function foo (literals,...values) {
    console.log(literals); // ['',' is ',' years old']
    console.log(values); // ['Billy',23]
    return 'foo';
}

var name = 'Billy';
var born = 1992;
var now = () => new Date().getFullYear();

var message = foo`${name} is ${now()-born} years old`;
// 'foo'

Happy Coding 😀

Discussion

pic
Editor guide