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:
pad with default values
I noticed that i mostly need the padLeft for time conversion / number padding
so i wrote this function
function padL(a,b,c){//string/number,length=2,char=0
return (new Array(b||2).join(c||0)+a).slice(-b)
}
This simple function supports Number or String as input
default pad is 2 chars
default char is 0
so i can simply write
padL(1);
// 01
if i add the second argument (pad width)
padL(1,3);
// 001
third parameter (pad char)
padL('zzz',10,'x');
// xxxxxxxzzz
EDIT
@BananaAcid
if you pass a undefined value or a 0 length string you get 0undefined
..so:
as suggested
function padL(a,b,c){//string/number,length=2,char=0
return (new Array((b||1)+1).join(c||0)+(a||'')).slice(-(b||2))
}
but this can also be achieved in a shorter way.
function padL(a,b,c){//string/number,length=2,char=0
return (new Array(b||2).join(c||0)+(a||c||0)).slice(-b)
}
works also with:
padL(0)
padL(NaN)
padL('')
padL(undefined)
padL(false)
And if you want to be able to pad in both ways :
function pad(a,b,c,d){//string/number,length=2,char=0,0/false=Left-1/true=Right
return a=(a||c||0),c=new Array(b||2).join(c||0),d?(a+c).slice(0,b):(c+a).slice(-b)
}
which can be written in a shorter way without using slice.
function pad(a,b,c,d){
return a=(a||c||0)+'',b=new Array((++b||3)-a.length).join(c||0),d?a+b:b+a
}
/*
Usage:
pad(
input // (int or string) or undefined,NaN,false,empty string
// default:0 or PadCharacter
// optional
,PadLength // (int) default:2
,PadCharacter // (string or int) default:'0'
,PadDirection // (bolean) default:0 (padLeft) - (true or 1) is padRight
)
*/
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:
var arrayOfNumbers=[1,2,3,4,5,6,7],
paddedArray=[],
len=arrayOfNumbers.length;
while(len--){
paddedArray[len]=('0000'+arrayOfNumbers[len]).slice(-4);
}
if you don't know how the max padding size based on the numbers inside the array.
var arrayOfNumbers=[1,2,3,4,5,6,7,49095],
paddedArray=[],
len=arrayOfNumbers.length;
// search the highest number
var arrayMax=Function.prototype.apply.bind(Math.max,null),
// get that string length
padSize=(arrayMax(arrayOfNumbers)+'').length,
// create a Padding string
padStr=new Array(padSize).join(0);
// and after you have all this static values cached start the loop.
while(len--){
paddedArray[len]=(padStr+arrayOfNumbers[len]).slice(-padSize);//substr(-padSize)
}
console.log(paddedArray);
/*
0: "00001"
1: "00002"
2: "00003"
3: "00004"
4: "00005"
5: "00006"
6: "00007"
7: "49095"
*/