Last active
October 24, 2015 04:02
-
-
Save prettycode/e458ba85a4b19b105674 to your computer and use it in GitHub Desktop.
Convenient String Formatter Helper/Utility Service Function in Angular JS
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
.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