Skip to content

Instantly share code, notes, and snippets.

@maurobaraldi
Last active November 24, 2015 10:58
Show Gist options
  • Save maurobaraldi/ce773fa6cccbad4258a4 to your computer and use it in GitHub Desktop.
Save maurobaraldi/ce773fa6cccbad4258a4 to your computer and use it in GitHub Desktop.
Javascript string.format <3
// from http://stackoverflow.com/a/4256130/841339
String.prototype.format = function() {
var formatted = this;
for (var i = 0; i < arguments.length; i++) {
var regexp = new RegExp('\\{'+i+'\\}', 'gi');
formatted = formatted.replace(regexp, arguments[i]);
}
return formatted;
};
@maurobaraldi
Copy link
Author

Usage

var myVar = "Hello {0}! Let's talk about {1}."
console.log(myVar.format("World", "Javascript"))

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