출처 : http://stackoverflow.com/questions/5366849/convert-1-to-0001-in-javascript








 

Just to demonstrate the flexibility of javascript: you can use a oneliner for this

function padLeft(nr, n, str){

    return Array(n-String(nr).length+1).join(str||'0')+nr;

}

//or as a Number prototype method:

Number.prototype.padLeft = function(n,str){

    return Array(n-String(this).length+1).join(str||'0')+this;

}

//examples

console.log(padLeft(23,5));       //=> '00023'

console.log((23).padLeft(5));     //=> '00023'

console.log((23).padLeft(5,' ')); //=> '   23'

console.log(padLeft(23,5,'>>'));  //=> '>>>>>>23'

 

 

If you want to use this for negative numbers also:

Number.prototype.padLeft = function(n,str){

    return (this < 0 ? '-' : '') +

            Array(n-String(Math.abs(this)).length+1)

             .join(str||'0') +

           (Math.abs(this));

}

console.log((-23).padLeft(5));     //=> '-00023'

Posted by motolies
,