js pad code example

Example 1: javascript print int with leading zeros

function padLeadingZeros(num, size) {
    var s = num+"";
    while (s.length < size) s = "0" + s;
    return s;
}
padLeadingZeros(57, 3);// "057"
padLeadingZeros(57, 4); //"0057"

Example 2: lpad javascript

str.padStart(targetLength [, padString])

Example 3: string padStart padEnd

let string = ‘Alice’; 
// padStart() — we assume our string needs to have 10 characters 
string.padStart(10, ‘o’); // returns ‘oooooAlice’
// padEnd() 
string.padEnd(10, ‘o’); // returns ‘Aliceooooo’;

Example 4: js number padding to number of characters

var n = 123

String("00000" + n).slice(-5); // returns 00123
("00000" + n).slice(-5); // returns 00123
("     " + n).slice(-5); // returns "  123" (with two spaces)