What is padStart() in JavaScript?

Overview

The padStart() method is a string method that is used to pad a string with another string. padStart() pads the current string with another until the resulting string reaches the specified length.

Syntax

// [length] = resulting string length
// [padString] = string to pad with current string
padStart([length], [padString])

Parameters

  • [length]: Denotes the length of the resulting string. This is the string length of the result or returned value.

  • [padString]: The string that you want to use to pad the current string. [padString] is applied to the current string from the start position. Note that this parameter is optional and the default is a space, " ".

Return value

The return value of the padString() method is a new string with the specified length ([length]) that is padded with the specified pad string ([padString]).

Example

Let’s pad a string in an easy way. We want to pad the string "ouch" with our pad string "O", the uppercase character "o", and a length of 7. This will result in the new string "OOOouch".

// create a string
let ourString = "ouch";
// pad the string
let paddedString = ourString.padStart(7, "O");
// log the string to console
console.log(paddedString); // "OOOouch"

Note: The length parameter should not be greater than the string length. Otherwise, it won’t be padded.

Example

When the length parameter is less than the string length, then no pad is added. Hence, the resulting length should be more than the current string length.

/*
length parameter(2) should be greater than
current string length ("ish").
*/
console.log("ish".padStart(2, "i")) // "ish"

Example

We can also use multiple pad characters. In the example below, we use "Ed" to pad the string "presso".

// create a string
let ourString = "presso";
// pad our string
let paddedString = ourString.padStart(8, "Ed")
// log padded string to console
console.log(paddedString); // "Edpresso"

Free Resources