DEV Community

John Au-Yeung
John Au-Yeung

Posted on

Introducing JavaScript Template Strings

Subscribe to my email list now at http://jauyeung.net/subscribe/

Follow me on Twitter at https://twitter.com/AuMayeung

Template strings are a powerful feature of modern JavaScript released in ES6. It lets us insert/interpolate variables and expressions into strings without needing to concatenate like in older versions of JavaScript. It allows us to create strings that are complex and contain dynamic elements. Another great thing that comes with template strings is tags. Tags are functions that take a string and the decomposed parts of the string as parameters and are great for converting strings to different entities.

The syntax for creating template strings is by using backticks to delimit them. For example, we can write:

`This is a string`

This is a very simple example of a template string. All the content is constant and there are no variables or expressions in it. To add variables and or expressions to a string, we can do the following.

Interpolating Variables and Expressions

// New JS with templates and interpolation  
const oldEnoughToDrink = age >= 21;  
const oldEnough = `You are ${oldEnoughToDrink ? 'old enough' : 'too young'} to drink.`

We insert a variable or expression by adding a dollar sign $ and curly braces {} into the string `${variable}`. This is much better than the alternative in old JavaScript where we had to concatenate a string like the following:

// Old JS using concatenation  
const oldEnoughToDrink = age >= 21;  
const oldEnough = 'You are ' + (oldEnoughToDrink ? 'old enough' : 'too young') + ' to drink.'

As we can see it’s easy to make syntax errors with the old concatenation syntax if we have complex variables and expressions. Therefore template strings are a great improvement from what we had before.

If we want to use the backtick character in the content of string just put a \ before the backtick character in the string. => `will have a literal ` backtick`

Multiline Strings

Another great feature of template strings is that we can have strings with multiple lines for better code readability. This cannot be done in an easy way with the old style of strings. With the old style of strings, we had to concatenate each line of the string to put long strings in multiple lines like the following examples:

const multilineStr = 'This is a very long string' +   
  'that spans multiple lines.'const multllineStr2 = 'At vero eos et accusamus et iusto odio' + 'dignissimos ducimus qui blanditiis praesentium voluptatum ' + 'deleniti atque corrupti quos dolores et quas molestias ' + 'excepturi sint occaecati cupiditate non provident, ' +   
'similique sunt in culpa qui ' +   
'officia deserunt mollitia animi.'

As we can see, this will become really painful is we have many more lines. It’s very frustrating to have all those plus signs and divide the string into multiple lines.

With template strings, we don’t have this problem:

const longString = `At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi.`

This is much better than concatenating strings together. It takes a lot less time to write the code and a lower probability of syntax errors. It’s also much more readable.

Note that this method does add an actual new like to the string \n and if you don’t want the string to have multiple lines in its final format, just put a \ at the end of the line.

Nesting Templates

Template strings can be nested in each other. This is a great feature because many people want to create dynamic strings. Template strings allow us to nest regular strings or template strings within template strings. For example, we can write the following:

const oldEnoughToDrink = age >= 21;  
const oldEnough = `You are ${oldEnoughToDrink ? 'old enough' : 'too young'} to drink.`

We can write the same thing with the expression interpolated in the string with template strings instead:

const TOO_YOUNG = 'too young';  
const OLD_ENOUGH = 'old enough';
const oldEnoughToDrink = age >= 21;
const oldEnough = `You are ${oldEnoughToDrink ? OLD_ENOUGH : TOO_YOUNG} to drink.`

This case is simple, but with complex string combinations, it is very powerful to be able to add logic to how we build our strings.

Tagged Templates

With template strings, we can add something called tags in front of a template string. They are functions that take a string and the decomposed parts of the string as parameters. A tagged function decomposes the template string into an array as the first parameter, with each item of the array as the constant parts of the string. The additional parameters of the function are all the variables and expressions in the order in which they appear in the string.

const personOldTag = (strings, nameExp, ageExp, genderExp) => {  
  let str0 = strings[0]; // " is a "  
  let str1 = strings[1]; // " year old "  

  let oldStr;  
  if (ageExp > 75){  
    oldStr = 'senior';  
  } else {  
    oldStr = 'young';  
  }  

  // We can even return a string built using a template literal  
  return `${nameExp}${str0}${oldStr}${genderExp}.`;  
}

const name = 'Bob'  
const age = 80;  
const gender = 'male;
const result = personOldTag`${ name } is a ${ age } year old ${ gender }`;
// result should be `Bob is a senior man.`

Tagged templates are great for converting strings to anything you want since it’s just a regular function. However, it is a special function because the first parameter is an array containing the constant parts of the string. The rest of the parameters contain the returned values that each expression returns. This is great for manipulating the string and transforming the returned values to what we want.

The return value of tags can be anything you want. So we can return strings, arrays, objects, or anything else.

As we see in the function above, in the string that we put beside the personOldTag, we first interpolated the name, then the age , then the gender. So in the parameters, they also appear in this order — nameExp, ageEx, and genderExp. They are the evaluated versions of the name, age, and gender in the template string.

Since tags are functions, we can return anything we want:

const isOldTag = (strings, nameExp, ageExp, genderExp)=>{  
  let str0 = strings[0]; // " is a "  
  let str1 = strings[1]; // " year old "  
  return ageExp > 75  
}

const name = 'Bob'  
const age = 80;  
const gender = 'male;
const result = isOldTag`${ name } is a ${ age } year old ${ gender }`;
// result is true

As you can see, we can manipulate the data to return a boolean instead of a string. Template tags are a feature that’s only available for template strings. To do the same thing with the old style of strings, we have to decompose the strings with our own string manipulating code and the built-in string manipulation functions, which is nowhere near as flexible as using tags. It decomposes the parts of a string into arguments for you that get passed in the template tags.

Raw Strings

Template strings have a special raw property that you can get from tags. The raw property gets us the string without escaping the special characters, hence the property is called raw. To access the raw property of a string, we can follow the example:

const logTag = (strings) => {  
  console.log(strings.raw[0]);  
}  

logTag`line 1 \r\n line 2\`;  
// logs "line 1 \r\n line 2" including characters '\', 'r' and 'n'

This is handy for visualizing the string as-is with the special characters intact.

There’s also the String.raw tag where we can take a template string and return a string with the escape characters without actually escaping them to see the string in its full form. For example, with the String.raw tag, we can write:

let hello = String.raw`Hello\n${'world'}!`;  
// "Hi\nworld!"  

hello.length;  
// 13  

hello.split('').join(',');  
// "H,e,l,l,o,\,n,w,o,r,l,d,!"

As we can see, we have all the characters of the string with the expressions evaluated, but we keep the escape characters as is.

Support for Template Strings

Template strings are supported by almost all browsers that are regularly maintained today. The only major one that doesn’t support it right out of the box is Internet Explorer. However, browsers that do not support it can add it with Babel. Node.js also supports it in version 4 or later.

Template strings are the new standard for JavaScript strings. It is much better than strings before ES6 in that it supports interpolating expressions inside strings. We also have tagged templates which are just functions, with the decomposed parts of the template string as parameters. The constant string in the first parameter is the string in a decomposed array form, and the evaluated versions of the expressions in the order they appeared in the string are the remaining arguments. Tagged template functions can return any variable type.

The raw property of a string, which is available in tags, can get the string with the escape characters unescaped.

Oldest comments (0)