This JavaScript tutorial explains how to use the string approach called padStart() with syntax and examples.
Description
In JavaScript, padStart() is a string approach that is used to pad the start of a string with a specific string to a certain length. This kind of padding is on occasion known as left pad or lpad. Because the padStart() approach is a technique of the String object, it must be invoked through a unique instance of the String class.
Syntax
In JavaScript, the syntax for the padStart() technique is:
string.padStart(length [, pad_string]);
Parameters or Arguments
length The preferred size of the ensuing string after it has been padded. pad_string Optional. It is the particular string to pad to the begin of string. If this parameter is no longer provided, the padStart() technique will use a space as the pad character.
Returns
The padStart() technique returns a string that has been padded at the begin with the special string to the desired length.
Note
The padStart() method does not exchange the value of the unique string.
Example
Let’s take a seem to be at an instance 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 known as totn_string that is assigned the string fee of ‘TechOnTheNet’. We have then invoked the padStart() approach of the totn_string variable to pad the start of totn_string with ‘A’ until it is the preferred size of 20 characters.
We have written the output of the padStart() approach to the net browser console log, for demonstration purposes, to exhibit what the padStart() technique returns.
The following will be output to the internet browser console log:
AAAAAAAATechOnTheNet
As you can see, the padStart() technique brought 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() approach that is a couple of characters (and no longer simply 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 sixteen characters. The padStart() method lower back the string price of ‘xyzxTechOnTheNet’.
Notice that the ensuing string started with the ‘xyzx’ character. This took place due to the fact the sequence of characters in the pad_string persevered to repeat until the resulting string was the preferred size of 16 characters. In this case, it stopped repeating at the ‘x’ character.
Leave a Review