Javascript String padStart()

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

Example


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

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()

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.


Recommended Reading: JavaScript String padEnd()