Friday, 25 April 2014

A simple pad function in Javascript

I have been working on a small time tracking tool in angularJS, and I needed padding for strings in a digital clock. I had a quick search and although I found quite a few different implementations, none of them were very satisfactory.

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