What is the String.padStart() method in JavaScript?
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.
Syntax
The padStart() method can be declared as shown in the code snippet below.
str.padStart( len, pad )
Parameters
str: The string to be padded.len: The length ofstrafter padding it.pad: The string that will be added to the start ofstrto pad it.
- If
lenis less than the length ofstr’ before padding, thepadStart()method returnsstritself without padding it.- If the length of
padis greater thanlen,padis truncated.- If the length of
strbefore padding and the length ofpadis greater thanlen,padis repeatedly appended at the start ofstr. This is done until its length becomes equal tolen.
Return value
The padStart() method returns a string of the length of len, which is str added with pad at the start.
Browser compatibility
The padStart() method is supported by the following browsers:
- Google Chrome 57
- Firefox 48
- Edge 15
- Safari 10
- Opera 44
Code
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'));
Explanation
- In line 1, we declare a string,
str. - The
padStart()method is used in lines 3,5,7 and 9 to padstrwith the string,hi.