Code Logo

Pad String with padStart()

Published at25 Jul 2026
JavaScript String Handling Easy 0 views
Like0

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

Example 1
Input
"abc",5,"x"
Output
"xxabc"
Explanation

Pad with x's

Example 2
Input
"hello",8,"-"
Output
"---hello"
Explanation

Pad with hyphens

Example 3
Input
"test",4,"*"
Output
"test"
Explanation

Already at target length

Example 4
Input
"42",4,"0"
Output
"0042"
Explanation

Pad number with leading zeros

Example 5
Input
"5",3,"0"
Output
"005"
Explanation

Pad 5 to length 3 with zeros

Algorithm Flow

Recommendation Algorithm Flow for Pad String with padStart()
Recommendation Algorithm Flow for Pad String with padStart()

Solution Approach

function solution(str, len, pad) {
  return str.padStart(len, pad);
}

Best Answers

javascript - Approach 1
function solution(str, len, pad) {
  return str.padStart(len, pad);
}