Created
May 29, 2013 11:40
-
-
Save jlis/5669677 to your computer and use it in GitHub Desktop.
Javascript format function to replace placeholders in a string with content
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
// usage: | |
// string.format({key: replacement}) | |
// | |
// example: | |
// 'Hello {name}, how are you doing? I am doing {mood}.'.format({name: 'Mike', mood: 'fine'}); | |
String.prototype.format = function() { | |
var formatted = this; | |
if (arguments.length && typeof arguments[0] == 'object') { | |
var vars = arguments[0]; | |
for (v in vars) { | |
var regexp = new RegExp('\\{'+v+'\\}', 'gi'); | |
formatted = formatted.replace(regexp, vars[v]); | |
} | |
} | |
return formatted; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment