javascript pad zeros left 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: javascript padstart

export function padStart(number, digits = 2, emptyDigit = 0) {
	let length = 0;
	let n = Math.abs(number);
	let absoluteNumber = n;
	do {
		n /= 10;
		length++;
	} while (n >= 1);
	const prefix = Array(Math.max((digits - length) + 1, 0)).join(emptyDigit);
	return number < 0 ? `-${prefix}${absoluteNumber}` : prefix + number;
}

export default padStart;