Skip to content

Instantly share code, notes, and snippets.

@jarrodhroberson
Last active August 29, 2015 13:56
Show Gist options
  • Save jarrodhroberson/8806794 to your computer and use it in GitHub Desktop.
Save jarrodhroberson/8806794 to your computer and use it in GitHub Desktop.
// Only add if it doesn't exist yet!
if (!String.prototype.format) {
String.prototype.format = function() {
var str = this.toString();
if (!arguments.length)
return str;
var args = typeof arguments[0],
args = (("string" == args || "number" == args) ? arguments : arguments[0]);
for (arg in args)
str = str.replace(RegExp("\\{" + arg + "\\}", "gi"), args[arg]);
return str;
}
}
@jarrodhroberson
Copy link
Author

Usage is :

'{0} {1}!'.format('Hello', 'World');

results in

Hello World!

or

'{greeting} {name}!'.format({ greeting:'Hello', name:'World'});

results in

Hello World!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment