ES6 / ES2015 Template Strings

Basic literal string creation

ES6 Template strings are here to make your life easier. They involve wrapping your text in backticks.

var text = `I'm the new and "improved" way to write a string`;  

As you can see from the above example, there's no need to escape single or double quotes, but there has to be more useful stuff we can apply to template strings, hasn't there?

Variable interpolation

How about passing that variable into your string? Well, you can use the ${expression} notation for that.

var today = new Date(),  
    text = `the time and date is ${today.toLocaleString()}`;

Multiline strings

It's a simple as this.

var text = `In ES5 this is  
 not valid.`;

The biggest potential is when you mix multi-line strings with interpolated variables. Then you can have some real fun.

var html = `  
    <img src="/images/${imageSrc}" alt="${imageAlt}" />

N.B. Keeping the spacing correct in multi-line variables will also produced well formatted HTML when you render the string.

So there we have it, a quick introduction to some nifty new ES6 features. Stay tuned for more, and as always, feel free to leave a comment.