September 07, 2011

Cross browser Leading Zeros with JavaScript

This is a short entry for further reference

Left padding an integer with zeros was never so easy. Can't believe this ended up working.

function LeadWithZeros(num, pad) {
    return (Array(pad).join('0') + num).slice(-pad);
}

LeadWithZeros(5, 3) === '005';
LeadWithZeros(65, 3) === '065';
LeadWithZeros(120, 3) === '120';

No comments:

Post a Comment