#Ridiculously simple string formatting in JavaScript

Note: this was originally written in January 2012. Template strings are a part of the ES6 standard and are quite nice. This entry remains for historical purposes.

Inserting variables into strings is incredibly easy in some languages, but it’s a bit of a pain in JavaScript. Gluing bits of text and variables together is error prone and hard to read.

Here’s a simple extension to the .toString method on the Object prototype to allow variable insertion using %markers% %like% %this%. Of course, modifying the Object prototype in production code is a pretty terrible idea – this implementation is more of a wistful sigh towards a syntax that would be wonderful.

(function() {
  var originalToString = Object.prototype.toString;
  Object.prototype.toString = function(format) {
    if(typeof(format) !== 'string') {
      return originalToString.call(this);
    }

    return format.replace(/%([^%]+)%/g, function(_, key) {
      return this.hasOwnProperty(key) ? this[key] : '';
    }.bind(this));
  }
})();

So, here’s how it would work. You’d have an object with named values in it, and you’d pass your format string to its toString method:

var data = {
  'name': 'Mark',
  'loc': 'California'
}

console.log(data.toString("Hello. My name is %name%, and I am in %loc%."));

I really wish this was part of the standard.