The padStart()
method is used to pad the beginning of a string with another string until the resulting string reaches a given length. This string method is particularly useful for formatting strings, such as adding leading zeros to numbers.
Syntax
str.padStart(targetLength [, padString])
targetLength
is the length of the resulting string once the original string has been padded. If this value is less than the original string’s length, the string is returned as-is.
padString
(optional) is the string to pad the current string with. If the padString
is too long to stay within the target length, it will be truncated. The default value is " "
(a single space).
In the following example, the padStart()
method pads the original string “7
” with leading zeros until the length of the resulting string is 3.
Example
const str = "7";
const paddedStr = str.padStart(3, "0");
console.log(paddedStr); // Output: "007"
Another common use case is formatting months, days, hours, minutes, or seconds to ensure they have two digits. In the following example, the numbers are converted to a string and then padded with a leading zero to ensure it has two digits.
Example
const month = 9;
const formattedMonth = String(month).padStart(2, "0");
console.log(formattedMonth); // Output: "09"
const day = 4;
const formattedDay = String(day).padStart(2, "0");
console.log(formattedDay); // Output: "04"
const hour = 7;
const formattedHour = String(hour).padStart(2, "0");
console.log(formattedHour); // Output: "07"
const minute = 22;
const formattedMinute = String(minute).padStart(2, "0");
console.log(formattedMinute); // Output: "22"
const second = 5;
const formattedSecond = String(second).padStart(2, "0");
console.log(formattedSecond); // Output: "05"
Each value, such as month, day, hour, minute, or second, is converted to a string and then formatted using the padStart()
method to ensure it has two digits.
The final code snippet with padStart(8, "0").trim()
pads the string str
and then trims any leading or trailing whitespace.
Example
const str = " 425 568";
const paddedStr = str.padStart(8, "0").trim();
console.log(paddedStr); // Output: "425 568"
padStart(8, "0")
doesn’t add any padding to str
because its length (" 425 568"
) is already equal to the specified length (8 characters). After calling .trim()
, the leading space is removed, resulting in "425 568"
.