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.
String.prototype.padStart()
andString.prototype.padEnd()
are currently TC39 candidate proposals: see github.com/tc39/proposal-string-pad-start-end (only available in Firefox as of April 2016; a polyfill is available).Array manipulations are really slow compared to simple string concat. Of course, benchmark for your use case.
Here's my take
I'm not so sure about it's performance, but I find it much more readable than other options I saw around here...
pad with default values
I noticed that i mostly need the padLeft for time conversion / number padding
so i wrote this function
This simple function supports Number or String as input
default pad is 2 chars
default char is 0
so i can simply write
if i add the second argument (pad width)
third parameter (pad char)
EDIT @BananaAcid if you pass a undefined value or a 0 length string you get
0undefined
..so:as suggested
but this can also be achieved in a shorter way.
works also with:
And if you want to be able to pad in both ways :
which can be written in a shorter way without using slice.
now if you try to pad 'averylongword' with 2 ... thats not my problem.
Said that i give you a tip.
Most of the time if you pad you do it for the same value N times.
Using any type of function inside a loop slows down the loop!!!
So if you just wanna pad left some numbers inside a long list don't use functions to do this simple thing.
use something like this:
if you don't know how the max padding size based on the numbers inside the array.
I found this solution here and this is for me much much simpler:
And here I made an extension to the string object:
An example to use it:
This will return a time in the format "15:30"
It's 2014, and I suggest a Javascript string-padding function. Ha!
Bare-bones: right-pad with spaces
Fancy: pad with options
Usage (fancy):