Welcome to the second part of my series about ECMAScript 6! One of my favorite new web standards of Microsoft Edge, the new browser rendering engine we’re creating at Microsoft, is the extensive support it offers for ECMAScript 6. So I wrote this series to walk you through some of the cool things you can do with ECMAScript 6 when writing large applications for the web.
In the first installment, I covered Class and Inheritance. In this article, I’ll focus on template strings based on my personal experience creating embedded expressions.
Resolving the Line Return Problem
When working on Babylon.js, I have to deal with shaders code which can be seen, for the sake of comprehension, like a big bunch of text (which looks like C).
You can find an example in this GitHub repository.
The problem when dealing with long text in JavaScript is the line return. How many times have you written this kind of thing?
var myTooLongString = "A long time ago, in a galaxy far," + "far away...." + "It is a period of civil war." + "Rebel spaceships, striking" + "from a hidden base, have won" + "their first victory against" + "the evil Galactic Empire.";
When you have to work with shaders that are 200+ lines long, this quickly becomes a real pain.
Thankfully, ECMAScript 6 comes with the new template strings feature. Among other wonders, a template string directly supports multiline strings:
var myTooLongString = `A long time ago, in a galaxy far far away.... It is a period of civil war. Rebel spaceships, striking from a hidden base, have won their first victory against the evil Galactic Empire`;
Because all characters are significant inside a template string, I cannot add leading whitespaces.
Now as JavaScript developers we have three ways to define strings:
- with “”
- with ‘’
- with `` (also known as back-tick or grave accent)
So What About the Template Part Then?
Multiline
support is not the only feature of template strings. Indeed, you can also use template strings to substitute placeholders with variables values, as you may
have done with printf
in C/C++ or string.Format
in C#:
var items = []; items.push("banana"); items.push("tomato"); items.push("light saber"); var total = 100.5; result.innerHTML = `You have ${items.length} item(s) in your basket for a total of $${total}`;
This code produces the following output:
You have 3 item(s) in your basket for a total of $100.5
Pretty handy, right?
Remember the ECMAScript 5 way:
result.innerHTML = "You have " + items.length + " item(s) in your basket for a total of $" + total;
Going Further With Tags
The final stage of template strings specification is about adding a custom function before the string itself to create a tagged template string:
var myUselessFunction = function (strings,...values) { var output = ""; for (var index = 0; index < values.length; index++) { output += strings[index] + values[index]; } output += strings[index] return output; } result.innerHTML = myUselessFunction `You have ${items.length} item(s) in your basket for a total of $${total}`;
The function here is used to get access to both the constant string part and the evaluated variables values.
In the previous example, strings and values are the following:
- strings[0] = “You have “
- values[0] = 3
- strings[1] = “items in your basket for a total of $”
- values[1] = 100.5
- strings[2] = “”
As you can see, every values[n] is surrounded by constants strings (strings[n] and strings[n + 1]).
This allows you to control how the final output string is built. In my previous example, I only reproduced the basic behavior of template strings, but we can go further and add cool processing on your string.
For instance, here is a piece of code to block strings that try to inject custom DOM elements:
var items = []; items.push("banana"); items.push("tomato"); items.push("light saber"); var total = "Trying to hijack your site <BR>"; var myTagFunction = function (strings,...values) { var output = ""; for (var index = 0; index < values.length; index++) { var valueString = values[index].toString(); if (valueString.indexOf("<") !== -1) { // Far more complex tests can be implemented here :) return "String analyzed and refused!"; } output += strings[index] + values[index]; } output += strings[index] return output; } result.innerHTML = myTagFunction `You have ${items.length} item(s) in your basket for a total of $${total}`;
Tagged template strings can be used for a lot of things like security, localization, creating your own domain specific language, etc.
Raw Strings
Tag
functions have a special option when accessing strings constants: They can use strings.raw
to get the unescaped string values. For instance, in this case \n
will not be
seen as only one character but actually two: \
and n
.
The main goal is to allow you to access the string as it was entered:
var myRawFunction = function (strings,...values) { var output = ""; for (var index = 0; index < values.length; index++) { output += strings.raw[index] + values[index]; } output += strings.raw[index] console.log(strings.length, values.length); return output; } result.innerHTML = myRawFunction `You have ${items.length} item(s) in your basket\n.For a total of $${total}`;
This code generates the following output:
You have 3 item(s) in your basket\n.For a total of $100.5
You can
also use a new function of String: String.raw()
. This function is a
built-in function that does exactly what my previous example does:
result.innerHTML = String.raw `You have ${items.length} item(s) in your basket\n.For a total of $${total}`;
Conclusion
Microsoft Edge and the latest versions of Chrome (41+), Opera(28+) and Firefox (35+) support template strings, and you can track the level of overall ECMAScript 6 support here. So if you are targeting the modern web, there is no reason not to embrace template strings.
For a full view of what new web standards and features are coming in Microsoft Edge—like WebAudio—you can see the full list at dev.modern.ie/platform/status.
More Hands-On With JavaScript
It might surprise you a bit, but Microsoft has a bunch of free learning on many open source JavaScript topics, and we’re on a mission to create a lot more with Microsoft Edge. Check out my own:
- Introduction to WebGL 3D with HTML5 and Babylon.JS
- Building a Single Page Application with ASP.NET and AngularJS
- Cutting Edge Graphics in HTML
Or our team’s learning series:
- Practical Performance Tips to Make your HTML/JavaScript Faster (a 7-part series from responsive design to casual games to performance optimization)
- The Modern Web Platform Jump Start (the fundamentals of HTML, CSS, and JS)
- Developing Universal Windows App with HTML and JavaScript Jump Start (use the JS you’ve already created to build an app)
And some free tools: Visual Studio Community, Azure Trial, and cross-browser testing tools for Mac, Linux, or Windows.
This article is part of the web dev tech series from Microsoft. We’re excited to share Microsoft Edge and the new EdgeHTML rendering engine with you. Get free virtual machines or test remotely on your Mac, iOS, Android, or Windows device @ http://dev.modern.ie/.
Comments