Friday, December 8, 2017

Zero (or any character) Padding in javascript / jquery


This is a small manual function written in javascript to pad a certain character to a string. In practical, the string usually can a number which needs to be formatted in order to display properly. These numbers can be days, months or year for a date viewer or any number which follows a padding pattern before some operations.

    // obj : string you want to pad.
    // _lenght : length of you padded result string
    // paddingChar : the padding character which you want to add
    function Padding(obj, _length, paddingChar) {

        var str = String(obj);             
        var returnStr = "";
        if (str.length < _length) {
            for (var i = str.length ; i < parseInt(_length) ; i++) { returnStr += paddingChar; }
        }

        return returnStr + str;
    }

Call the function like this :

var result = Padding(12,5,'0');

It should return '00012'.

No comments:

Post a Comment