Skip to content

Instantly share code, notes, and snippets.

@prettycode
Last active October 24, 2015 04:02
Show Gist options
  • Save prettycode/e458ba85a4b19b105674 to your computer and use it in GitHub Desktop.
Save prettycode/e458ba85a4b19b105674 to your computer and use it in GitHub Desktop.
Convenient String Formatter Helper/Utility Service Function in Angular JS
.factory('formatString', [function() {
/* by Chris O'Brien, prettycode.org, MIT license */
return function formatString() {
var args = Array.prototype.slice.call(arguments),
format = args.shift(),
match;
if (args.length === 1 && typeof args[0] === 'object') {
args = args[0];
}
for (var i = 0; !!(match = /{(\d+|\w+)?}/gm.exec(format)); i++) {
var key = match[1];
format = key
? format.replace(new RegExp('\\{' + key + '\\}', 'gm'), args[key])
: format.replace('{}', args[i]);
}
return format;
};
}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment