Using Crockford's supplant function in Javascript

Posted by Richard Lucas on Nov 1 2013

The supplant function is easy to use for string interpolation and a nice introduction templating in JavaScript.

Here’s the function from Douglas Crockford’s website:

1
2
3
4
5
6
7
8
9
if (!String.prototype.supplant) {
String.prototype.supplant = function (o) {
return this.replace(/\{([^{}]*)\}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
});
};
}

So how is it used. Here’s a quick example:

var greeting = "Hi, I'm {name}".supplant[{name:"Richard"}];

Output: “Hi, I’m Richard”

Another example:

1
2
3
4
5
6
7
myObj = {
name: 'Richard',
city: 'Columbus',
state: 'Ohio'
};
var myInfo = "Hi, my name is {name} and I'm from {city}, {state}".supplant(myObj);

Output: “Hi, my name is Richard and I’m from Columbus, Ohio”

You can use it with arrays:

1
2
3
var names = ["Richard", "Yalcin", "Dan", "Mike", "Kerry"];
var classmates = "My classmates are {0}, {1}, {2}, {3}, and {4}".supplant(names);

Output: “My classmates are Richard, Yalcin, Dan, Mike, and Kerry”

These are a few examples, hopefully you do find them helpful. Supplant does take some criticism for being inefficient as well as unescapable, which are both founded. So, you may want to use supplant sparingly, but it’s certainly a great tool in learning JavaScript.

Here’s a stack overflow post that discusses it further as well.

And as you delve deeper into string interpolation and templating, I suggest looking into Handlebars.js or Mustache.

As always, if you have any questions, please don’t hesitate to ask.

Cheers!