The padStart()
method pads a string with another string so that the string to be padded reaches a given length. Since the padding is applied to the left of the string as its starts, it is also called left padding.
The padStart()
method can be declared as shown in the code snippet below.
str.padStart( len, pad )
str
: The string to be padded.len
: The length of str
after padding it.pad
: The string that will be added to the start of str
to pad it.
- If
len
is less than the length ofstr
ā before padding, thepadStart()
method returnsstr
itself without padding it.- If the length of
pad
is greater thanlen
,pad
is truncated.- If the length of
str
before padding and the length ofpad
is greater thanlen
,pad
is repeatedly appended at the start ofstr
. This is done until its length becomes equal tolen
.
The padStart()
method returns a string of the length of len
, which is str
added with pad
at the start.
The padStart()
method is supported by the following browsers:
The code snippet below demonstrates the use of the padStart()
method.
const str = 'Hello World!';console.log(str.padStart(14, 'Hi'));console.log(str.padStart(17, 'Hi'));console.log(str.padStart(12, 'Hi'));console.log(str.padStart(13, 'Hi'));
str
.padStart()
method is used in lines 3,5,7 and 9 to pad str
with the string, hi
.