JavaScript String padStart()

Total
0
Shares

In this tutorial, we will learn about the JavaScript String padStart() method with examples.

The JavaScript String.prototype.padStart() method pads the current string with another string until the resulting string reaches the given length. The padding is applied from the start of the current string.

padStart() Example

const text = "ItsJavaScript"
console.log(text.padStart(25, '.'))

Output

............ItsJavaScript

padStart() Syntax

The syntax of the JavaScript padStart() method is as follows.

str.padStart(targetLength, padString)

Here the str is the string or the string variable.

padStart() Parameter

The JavaScript padStart() method can take two parameters:

  • targetLength – The length of the final string after the current string has been padded. If the targetLength is less than the length of the string, then the string is returned unmodified without padding.
  • padString (Optional) – The padString is an optional parameter that is used to pad the string. The default value is ” ” 

Note: If padString is too long, it will be truncated from the end to meet the targetLength.

padStart() Return Value

The padStart() method returns the string of the specified length with the padString applied at the start of the string.

Example 1 – How padStart() method works in JavaScript?

// How to pad a string at the start
const text = "Microsoft"
console.log(text.padStart(20,"."))

// Pad string in case length is less than the string length
const text2 = "LinkedIn"
console.log(text2.padStart(5,'Corp'))

// pad another string at the start
const text3 = "Apple"
console.log(text3.padStart(9, 'Its '))

// the padstring gets truncated to meet the target length
const text4 = "ItsJavaScript"
console.log(text4.padStart(20, 'Welcome to '))

Output

...........Microsoft
LinkedIn
Its Apple
WelcomeItsJavaScript

Example 2 – Working of padStart() method with default value

The padString is an optional parameter that is used to pad the string. The default value is ” ” if we do not provide it.

// How to pad a string at the end
const text = "Microsoft"
console.log(text.padStart(20))

// Pad string in case length is less than the string length
const text2 = "LinkedIn"
console.log(text2.padStart(5))

Output

           Microsoft
LinkedIn
Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Get notified on the latest articles

You May Also Like