Emulating ES6 template strings in ES5 with _.template() from lodash

A cool new feature in ECMAScript 2015 (ES6) is template strings. It lets you put variables in your strings without the awkward string concatenation.

This ES5 code:

 var message = 'Hello, ' + user.firstName + ' ' + user.lastName;

could be written like this in ES6:

var message = `Hello, ${user.firstName} ${user.lastName}`;

If you aren’t able to use ES6 yet and wish to emulate that feature, you can get a rough approximation with _.template() from lodash. You just need to set the interpolate option to /\$\{([^\}]+)\}/gm. Then you build a little formatter function like this:

function fmtr(str, obj) {
    return _.template(_.isString(str) ? str : '', { interpolate: /\$\{([^\}]+)\}/gm })(obj);
}

With that function, you can use templates like this:

var message = fmtr('Hello, ${firstName} ${lastName}', user);

I’ve found it super useful in a number of projects and have packaged it up in a node.js module named fmtr.

While it isn’t as powerful as string templates in one way (you have to pass an object to it with the variables you want to substitute into the string), it is more powerful in another way. You can use it as the foundation for bigger and better things. For example, I built an LDAP escaper module named ldap-escape to prevent LDAP injection attacks; it escapes the values and then applies the template like this:

var safeDn = ldapEscape.dn('cn=${cn},dc=test', alice);