Last active
December 22, 2015 21:09
-
-
Save civersen/6531447 to your computer and use it in GitHub Desktop.
String format implementation with padding.
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
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