JavaScript String padStart() Tutorial

In this section, we will learn what the padStart() method is and how to use it.

JavaScript String padStart() Method

If we want to pad the start side of a string value with other characters, we can use the padStart() method.

JavaScript String padStart() Syntax

padStart(targetLength, padString)

String padStart() Method Parameters:

The method takes two arguments:

  1. The first argument is the final length of the padded string. For example, if the string value currently has a length of 10 characters and we want to pad its end side with 3 other characters, we need to set the first argument to 13 to match the current number of characters plus 3 other pad characters.
  2. The second argument is the string value that we want to pad the target string with. This second argument is optional and, if omitted, the default value which is a white-space will be used.

Note: if the length of the second argument is greater than the value specified as the first argument, then the second argument will be truncated automatically to fit the final length. Also, if the length of the second argument is less than what is needed to pad the target string, then the second argument will be repeated.

String padStart() Method Return Value:

The return value of this method is a new string that is a combination of the original string and the characters we used to pad that original string.

Example: JavaScript left pad

const name = "John Doe";

console.log(`The length of the 'name' identifier before padding: ${name.length}`);

const rep = name.padStart(20, "*");

console.log(`The length of the 'name' identifier after padding: ${name.length}`);

console.log(rep);

console.log(`The length of the 'rep' identifier: ${rep.length}`);

Output:

The length of the 'name' identifier before padding: 8

The length of the 'name' identifier after padding: 8

************John Doe

The length of the 'rep' identifier: 20

Example: JavaScript padding zeros

const name = "John Doe";

console.log(`The length of the 'name' identifier before padding: ${name.length}`);

const rep = name.padStart(20, "0");

console.log(`The length of the 'name' identifier after padding: ${name.length}`);

console.log(rep);

console.log(`The length of the 'rep' identifier: ${rep.length}`);

Output:

The length of the 'name' identifier before padding: 8

The length of the 'name' identifier after padding: 8

000000000000John Doe

The length of the 'rep' identifier: 20
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies