padstart javascript javascript code example

Example 1: 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;

Example 2: 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)