Skip to content

Instantly share code, notes, and snippets.

@civersen
Last active December 22, 2015 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save civersen/6531447 to your computer and use it in GitHub Desktop.
Save civersen/6531447 to your computer and use it in GitHub Desktop.
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