Javascript String padStart()

The padStart() method pads the current string with another string to the start.

Example

// string definition
let string1 = "CODE";

// padding "*" to the start of given string // until the length of final padded string reaches 10 let paddedString = string1.padStart(10, "*");
console.log(paddedString); // Output: ******CODE

padStart() Syntax

The syntax of the padStart() method is:

str.padStart(targetLength, padString)

Here, str is a string.


padStart() Parameters

The padStart() method takes two parameters:

  • targetLength - The length of the final string after the current string has been padded.
  • padString (optional) - The string to pad the current string with. Its default value is " ".

Note:

  • If padString is too long, it will be truncated from the end to meet targetLength.
  • For targetLength < str.length, the string is returned unmodified.

padStart() Return Value

  • Returns a String of the specified targetLength with padString applied from the start.

Example 1: Using padStart() Method

// string definition
let string1 = "CODE";

// padding "$" to the start of the string // until the length of final padded string reaches 10 let paddedString1 = string1.padStart(10, "$");
console.log(paddedString1);

Output

$$$$$$CODE

In the above example, we have assigned a string value "CODE" to string1 and used padStart() to pad "$" symbol to the starting of string1. Inside the method, we have also passed 10 as targetLength.

So the method returns the final string "$$$$$$CODE" with length 10.


Example 2: Using Multiple Character padString in padStart()

// string definition 
let string1 = "CODE";

// padding 'JavaScript' to the start of the string // until the length of padded string reaches 17 let paddedString2= string1.padStart(17, 'JavaScript');
console.log(paddedString2);

Output

JavaScriptJavCODE

In the above example, we have passed multiple characters "JavaScript" to padStart() and assigned the return value to paddedString2.

The method adds "JavaScript" to the start of "CODE" until the length of the final string becomes 17. That is, paddedString2 returns the final string "JavaScriptJavCODE" whose length is 17.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges