I am in need of a JavaScript function which can take a value and pad it to a given length (I need spaces, but anything would do). I found this:
Code:
String.prototype.pad = function(l, s, t){
return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
+ 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
+ this + s.substr(0, l - t) : this;
};
Example:
<script type="text/javascript">
//<![CDATA[
var s = "Jonas";
document.write(
'<h2>S = '.bold(), s, "</h2>",
'S.pad(20, "[]", 0) = '.bold(), s.pad(20, "[]", 0), "<br />",
'S.pad(20, "[====]", 1) = '.bold(), s.pad(20, "[====]", 1), "<br />",
'S.pad(20, "~", 2) = '.bold(), s.pad(20, "~", 2)
);
//]]>
</script>
But I have no idea what the heck it is doing and it doesn't seem to work for me.
Taking up Samuel's ideas, upward here. And remember an old SQL script, I tried with this:
It works in all the cases I could imagine:
http://www.webtoolkit.info/javascript_pad.html
It's a lot more readable.
And then you can do:
Here's a recursive approach to it.
An example...
es7 is just drafts and proposals right now, but if you wanted to track compatibility with the spec, your pad functions need:
From my polyfill library, but apply your own due diligence for prototype extensions.
A short way:
Example:
return: "001234"