Welcome to the second part of my series about ECMAScript 6! One of my favorite new web standards 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 here.
The problem when dealing with long-sized text in JavaScript is the line return. How many times did you write 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 200+ lines long shaders, 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 3 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 a template strings to substitute placeholders with variables values like 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 as long as 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) {
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 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 constant: 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 builtin 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 latest versions of Chrome (41+), Opera(28+) and Firefox (35+) supports 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 to not embrace template strings.
For a full view at 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 coming. Check out my own:
Or our team’s learning series:
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 @ dev.modern.ie.