So, I built one.
Quite simple really, but it will handle pretty much any type of input, and will pad both left and right.
Anyway, here it is.
function pad(input,size,paddingChar,direction){ input = String(input); size = size || 1; paddingChar = paddingChar|| 0; direction = direction?String(direction).toUpperCase():"LEFT"; var padString = Array(size).join(paddingChar); if(input.length < size){ if(direction == 'LEFT'){ input = (padString+input).slice(size*-1); }else if(direction == 'RIGHT'){ input = (input+padString).slice(0,size); } } return input; }
It is pretty easy to use:
To get Left padding:
pad(8,2,0) will return "08"
pad("234",5,0) will return "00234"
pad("top",5," ") will return " top"
To get right padding:
pad("top",5," ","RIGHT") will return "top "
If you like it, please feel free to use it (at your own risk, of course).
No comments:
Post a Comment