Learning ES6 - Strings

3 min read.

There have been some improvements to the ways you can create and work with Strings in ECMAScript 6. For example, new methods were added to the String object. However, the most interesting addition is the new string literal syntax called template strings, and that’s what I’m going to talk about today.

The Basics

The normal way to create strings is by using single, or double, quotes. like so:

var s1 = 'string with single quotes.';
var s2 = "string with double quotes.";

In ECMAScript 6, you can also use back ticks to create strings. This is the foundation for working with template strings. The big thing about template strings is that it brings string interpolation to javascript. This means that it just got a lot easier to build strings.

var s3 = `template string with back ticks`;

var name = 'John';
var s4 = 'hello ' + name + ', how are you?'; // old way of building strings.
var s5 = `hello ${name}, how are you?`; //the new cleaner way of building strings.

As you can see from the example above, we can use the ${...} to insert variables or JavaScript expressions into out string. It will use the toString method if it needs to convert the value into a string.

Multiline

By using the back tick syntax to create strings you no longer need to use the backslash (”\“) to indicate that the string will continue on the next line. You just write your multiline string as you want it to be. Bear in mind though that whitespaces won’t be ignored.

/* Two old ways of creating multiline strings */
var ow1 = 'multi \n' +
		  'line \n' +
          'string';

var ow2 = 'multi \
line \
string';

/* new way of creating multiline strings using back ticks */

var nw = `multi
	line
    string`;

console.log(nw); => 'multi
		line
    string' // => indentation is kept.

Tagged Templates

You can also tag template strings with functions that can be used to transform or manipulate the template in any way you want. A template function must follow the following structure:

function tag(stringArray, ...values) {
 // ... do stuff
 return <stringValue>;
}

It takes the strings in the template string as an array for its first parameter. Each parameter after that will be each value passed in to the template string using ${...}. Below is an example where we tag a template string to capitalize the name:

function capitilizeName(strings, name) {
    return strings[0] + name.capitalize() + strings[1]
}

var lowerCaseName = 'john';
var sentence = capitilizeName`Hello ${lowerCaseName}, how are you?`

console.log(sentence); // => Hello John, how are you?

Some possible use cases for tag functions could be preventing XSS when handling user data, or, when you are doing internationalization you can use tag functions for replacing strings with translated strings.

Previous Posts

If you liked this post checkout some of the previous posts in this series:

comments powered by Disqus