The padStart() function in TypeScript adds characters to the start of a string, serving as the opposite of padEnd(). It is particularly useful for formatting text or aligning numbers.
Syntax
string.padStart(targetLength: number, padString?: string): stringParameters:
- targetLength: Here you have to pass the length you want the final string to be, after adding padding.
- padString (Optional): The characters used for padding. Defaults, to spaces (' ') if not specified.
Return Value:
Returns a new string of the specified targetLength with the padString applied at the left side(i.e. beginning) of the current string.
Example 1: Padding with Spaces (Default)
In this example we use padStart(10) to add spaces to the beginning of str until its length is 10.
let str: string = "Geeks";
let paddedStr: string = str.padStart(10);
console.log(paddedStr);
Output:
GeeksExample 2: Padding with Zeros
In this example, the padStart() method pads the string with zeros to reach the target length.
let str: string = "123";
let paddedStr: string = str.padStart(5, "0");
console.log(paddedStr);
Output:
00123