Last active
December 12, 2015 12:39
-
-
Save jonathanmarvens/4773324 to your computer and use it in GitHub Desktop.
This function extends String adding minimal *printf-like* functionality.
This file contains hidden or 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
String.prototype.format = function (format_object) { | |
// TODO: Find better way to do this. Works great for now. | |
// I don't know how efficient this is, but it works. | |
var string_current = this.valueOf(); | |
var string_new = ''; | |
var format_matches = string_current.match(/\%\([a-zA-Z0-9_]+\)/g); // Definitely has edge cases. | |
var replace_object = {}; | |
if (format_matches.length > 0) { | |
for (var i = 0, j = format_matches.length; i < j; i++) { | |
var format_variable_length = format_matches[i].length; | |
var format_object_key = format_matches[i].substring(2, (format_variable_length - 1)); | |
if (format_object_key in format_object) { | |
replace_object[format_matches[i]] = format_object[format_object_key]; | |
} | |
} | |
string_new = string_current; | |
for (var key in replace_object) { | |
string_new = string_new.replace(key, replace_object[key]); | |
} | |
return string_new; | |
} else { return string_current; } | |
}; |
This file contains hidden or 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
String.prototype.format=function(a){var b=this.valueOf(),c="",d=b.match(/\%\([a-zA-Z0-9_]+\)/g),e={};if(d.length>0){for(var f=0,g=d.length;g>f;f++){var h=d[f].length,i=d[f].substring(2,h-1);i in a&&(e[d[f]]=a[i])}c=b;for(var j in e)c=c.replace(j,e[j]);return c}return b}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This makes it possible to do things like the following.