Skip to content

Instantly share code, notes, and snippets.

@jessedhillon
Created August 17, 2014 04:19
Show Gist options
  • Save jessedhillon/c93cb6ed15dfb0cc5cb1 to your computer and use it in GitHub Desktop.
Save jessedhillon/c93cb6ed15dfb0cc5cb1 to your computer and use it in GitHub Desktop.
Nice and crappy string formatting in Javascript
String.prototype.format = function(args) {
var paramsRegex = /\(([A-Za-z_0-9:.,\'\"]*)\)/;
var replaceRegex = /{([A-Za-z_0-9:.,\'\"\(\)]+)}/g;
var string = this;
return string.replace(replaceRegex, function(match, key) {
if(/:/.test(key)) {
var filters = key.split(':');
var value = args[filters.shift()];
for(var i = 0; i < filters.length; i++) {
var filterName = filters[i];
var params = [];
if(paramsRegex.test(filterName)) {
var params = paramsRegex.exec(filterName)[1];
if(params.length > 0) {
params = params.split(',').map(function(s) {
return eval(s.trim());
});
filterName = filterName.substring(0, filterName.indexOf("("));
}
}
var filter = value[filterName] || String.prototype[filterName] || args._filters[filterName];
if(typeof filter == 'function') {
var value = filter.apply(value, params);
} else {
var value = filter;
}
}
return value;
}
return typeof args[key] != 'undefined'
? args[key]
: match;
});
};
try {
"{firstName} {lastName:slice(0,5):toUpperCase} {initials:join('.')} (provided {initials:length} initials)".format({
firstName: 'Jesse',
lastName: 'Dhillon',
initials: ['Ph', 'D']
});
} catch(e) {
debugger;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment