Sunday, December 29, 2024
Google search engine
HomeLanguagesJavascriptJavaScript String padStart() Method

JavaScript String padStart() Method

The padStart() method in JavaScript is used to pad a string with another string until it reaches the given length. The padding is applied from the left end of the string. 

Syntax:

string.padStart(targetLength, padString)

Parameters:

This method accepts two parameters as mentioned above and described below:

  • targetLength: It is the length of the final string once the original string has been padded. If the value is less than the original string length, then the original string is returned.
  • padString: It is the string that is to be padded with the original string. If this value is too long to be within the targetLength, it is truncated from the end. The default used string is the space character (” “).

Return Value:

It returns the final string that is padded with the given string to the given length. 

Example 1: This example uses the padStart() method to pad given strings into another string. 

Javascript




// Function to implement padstart method
function padStrings() {
    // Input strings
    exString = "Hello123";
    exString2 = "Geeks";
     
    // Use padStart method to add
    // characters at the start
    prepended_out = exString.padStart(10, "$");
    prepended_out2 = exString2.padStart(10, "XX");
 
    // Display output
    console.log(prepended_out);
    console.log(prepended_out2);
}
 
//Function call
padStrings()


Output

$$Hello123
XXXXXGeeks

Example 2: This example uses the padStart() method to pad given numbers into another number or characters. 

Javascript




// Duntion to implement padStart
// and pad Numbers
function padNumbers() {
    // Input numbers
    exNumber = 999;
    exNumber2 = 123;
     
    // Using padStart to pad
    // input numbers
    prepended_out = String(exNumber).padStart(5, "0");
    prepended_out2 = String(exNumber2).padStart(5, "**");
 
    // Display output
    console.log(prepended_out);
    console.log(prepended_out2);
}
// Function call
padNumbers()


Output

00999
**123

We have a complete list of Javascript Strings, to check those please go through the Javascript String Complete reference article.

Supported Browsers: The browser supported by the padStart() method are listed below:

  • Google Chrome 57
  • Firefox
  • Edge
  • Safari
  • Opera

RELATED ARTICLES

Most Popular

Recent Comments