totn JavaScript

JavaScript: String padStart() method

This JavaScript tutorial explains how to use the string method called padStart() with syntax and examples.

Description

In JavaScript, padStart() is a string method that is used to pad the start of a string with a specific string to a certain length. This type of padding is sometimes called left pad or lpad. Because the padStart() method is a method of the String object, it must be invoked through a particular instance of the String class.

Syntax

In JavaScript, the syntax for the padStart() method is:

string.padStart(length [, pad_string]);

Parameters or Arguments

length
The desired length of the resulting string after it has been padded.
pad_string
Optional. It is the specified string to pad to the start of string. If this parameter is not provided, the padStart() method will use a space as the pad character.

Returns

The padStart() method returns a string that has been padded at the start with the specified string to the desired length.

Note

  • The padStart() method does not change the value of the original string.

Example

Let's take a look at an example of how to use the padStart() method in JavaScript.

For example:

var totn_string = 'TechOnTheNet';

console.log(totn_string.padStart(20,'A'));

In this example, we have declared a variable called totn_string that is assigned the string value of 'TechOnTheNet'. We have then invoked the padStart() method of the totn_string variable to pad the start of totn_string with 'A' until it is the desired length of 20 characters.

We have written the output of the padStart() method to the web browser console log, for demonstration purposes, to show what the padStart() method returns.

The following will be output to the web browser console log:

AAAAAAAATechOnTheNet

As you can see, the padStart() method added 8 'A' characters to the start of 'TechOnTheNet' to make the resulting string 'AAAAAAAATechOnTheNet' 20 characters in length.

Specifying Multiple Characters as the Pad String

Finally, let's see what happens if you specify a pad_string parameter for the padStart() method that is multiple characters (and not just a single character).

For example:

var totn_string = 'TechOnTheNet';

console.log(totn_string.padStart(16,'xyz'));

The following will be output to the web browser console log:

xyzxTechOnTheNet

In this example, we have invoked the padStart method() with a pad_string of 'xyz' and a desired length of 16 characters. The padStart() method returned the string value of 'xyzxTechOnTheNet'.

Notice that the resulting string started with the 'xyzx' character. This occurred because the sequence of characters in the pad_string continued to repeat until the resulting string was the desired length of 16 characters. In this case, it stopped repeating at the 'x' character.