Skip to content

Instantly share code, notes, and snippets.

@SafeerH
Last active August 29, 2015 14:23
Show Gist options
  • Save SafeerH/87b3b7eb890073343ccc to your computer and use it in GitHub Desktop.
Save SafeerH/87b3b7eb890073343ccc to your computer and use it in GitHub Desktop.
JavaScript Extensions (String.Format)
/* Format strings in JavaScript
* Usage:
* > "Hello {0}!".format('Safeer'); // Hello Safeer!
*
* > var str = "{0} is one of the most popular programming languages in the world. \
* This {1} contains some extension methods that can be used in your {0} code.";
* str.format('JavaScript', 'Gist');
*
*/
String.prototype.format = function() {
var str = this;
for (var i = 0; i < arguments.length; i++) {
var placeHolderRegExp = RegExp('(\{)' + i + '(\})', 'gm');
str = str.replace(placeHolderRegExp, arguments[i]);
}
return str + '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment