Pad String with padStart()
Write a JavaScript function that takes a string, a target length, and a pad character, and returns the string padded on the left with the pad character until the string reaches the target length using padStart().
String.prototype.padStart() is a JavaScript method introduced in ES2017 that pads the current string from the start with a given string until the resulting string reaches the given length. If the string is already at or longer than the target length, it is returned unchanged. Padding is applied from the left (start) of the string.
The padStart() method complements padEnd() which pads from the right. These methods are commonly used for formatting numbers with leading zeros, aligning text in columns, and creating fixed-width identifiers. The pad string can be multiple characters and is repeated as needed to fill the remaining space.
Time complexity is O(n) where n is the target length, as the engine creates a new string of that length. Space complexity is O(n) for the new string. The original string is not modified (strings are immutable in JavaScript).
Edge cases include padding with multi-character strings, target length shorter than the original string (returns original), empty pad string (behavior varies), and ensuring the method handles various character types including Unicode.
Example Input & Output
Pad with x's
Pad with hyphens
Already at target length
Pad number with leading zeros
Pad 5 to length 3 with zeros
Algorithm Flow

Solution Approach
Best Answers
function solution(str, len, pad) {
return str.padStart(len, pad);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
