Skip to content

Instantly share code, notes, and snippets.

@civersen
Last active Dec 22, 2015
Embed
What would you like to do?
String format implementation with padding.
String.prototype.format = String.prototype.f = function () {
var s = this;
for (var i = 0; i < arguments.length; i++) {
var m = s.match("\\{(" + i + ")(:.*?)?\\}", "gm");
if (m) {
if (m[2]) {
var x = m[2].substring(1);
if (x.search("^(.)\\1+$") > -1) {
var p = arguments[parseInt(m[1], 10)].toString();
while (p.length < x.length) {
p = x.substring(0, 1) + p.toString();
}
s = s.replace(m[0], p);
}
} else {
s = s.replace(m[0], arguments[parseInt(m[1], 10)]);
}
}
}
return s.toString();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment