Skip to content

Instantly share code, notes, and snippets.

@neatnick
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neatnick/2733b760a99ca1285e12 to your computer and use it in GitHub Desktop.
Save neatnick/2733b760a99ca1285e12 to your computer and use it in GitHub Desktop.
Python-like string formatting for JavaScript.
Array.prototype.flatten = function() {
return this.reduce(function(prev, cur) {
var more = [].concat(cur).some(Array.isArray);
return prev.concat(more ? cur.flatten() : cur);
},[]);
};
String.prototype.format = function () {
var content = this;
// regular for loop would probably be more efficient than the forEach
Array.prototype.slice.call(arguments).flatten().forEach(function (item, index) {
var pattern = '\\{' + index + '\\}',
re = new RegExp(pattern, "g");
content = content.replace(re, item);
});
return content;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment