Last Updated: February 25, 2016
·
1.714K
· ocodo

String.template()

This is just a little helper method I use in JavaScript a fair bit, it's an extension of the String class that provides basic parameter replacement, you could equally call it String.format() or even String.$() without angering the gods ... either way, it's a convenient and minimal way to doing interpolated strings in JS.

String.prototype.template = function (o) {
    return this.replace(/{([^{}]*)}/g,
                  function (a, b) {
                    var r = o[b];
                    return typeof r === 'string' ||
                           typeof r === 'number' ?
                           r : a;
                  }
           );
    };

Usage is simple and reasonably flexible, although there's no printf or C#'s String.format style formatting.

"{0} an array is {1}".template(["Using","simple"]);

Or for a bit of semantic richness a use a POO (plain old object)

"Your {list} list has {count} entries.".
                          template(
                               {
                                 list: "Contacts", 
                                 count: 120
                               }); 

1 Response
Add your response

Nice snippet. Here's a shorter version:
String.prototype.template = function() { var args = arguments; return this.replace(/\{([^}]+?)\}/g, function(_, match) { return args[match]; }); };

http://jsbin.com/ojeriz/1/edit

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip