JavaScript(JS) string method - padstart

htt‮//:sp‬www.theitroad.com

The padStart() method is a string method in JavaScript that is used to pad the start of a string with a specified character or set of characters until it reaches a specified length.

Here is the syntax for the padStart() method:

str.padStart(targetLength [, padString])

Here, str is the original string you want to pad, targetLength is the length of the resulting padded string, and padString is an optional string that specifies the characters to use for padding. If padString is not provided, the string is padded with spaces.

The padStart() method returns the padded string.

Here is an example of using the padStart() method:

let str = "hello";
let result = str.padStart(10, ".");
console.log(result); // ".....hello"

In the example above, the padStart() method pads the str with the "." character until it reaches a length of 10 characters. The resulting padded string is ".....hello".

If the length of the original string is greater than or equal to the specified targetLength, the padStart() method does not pad the string and returns the original string unchanged.

Here is an example of using the padStart() method with a custom padding string:

let str = "hello";
let result = str.padStart(10, "123");
console.log(result); // "12312hello"

In the example above, the padStart() method pads the str with the "123" string until it reaches a length of 10 characters. Since the "123" string is repeated to fill the padding, the resulting padded string is "12312hello".