Python has this beautiful function to turn this:
bar1 = \'foobar\'
bar2 = \'jumped\'
bar3 = \'dog\'
foo = \'The lazy \' + bar3 + \' \' + bar2 \' over the \'
Here's my first attempt. Feel free to point out flaws.
Example: http://jsfiddle.net/wFb2p/5/
String.prototype.format = function() {
var str = this;
var i = 0;
var len = arguments.length;
var matches = str.match(/{}/g);
if( !matches || matches.length !== len ) {
throw "wrong number of arguments";
}
while( i < len ) {
str = str.replace(/{}/, arguments[i] );
i++;
}
return str;
};
EDIT: Made it a bit more efficient by eliminating the .match() call in the while statement.
EDIT: Changed it so that the same error is thrown if you don't pass any arguments.