Last active
August 29, 2015 14:23
-
-
Save SafeerH/87b3b7eb890073343ccc to your computer and use it in GitHub Desktop.
JavaScript Extensions (String.Format)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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