Open In App

TypeScript String padStart() method

Last Updated : 15 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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): string

Parameters:

  • 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.

TypeScript
let str: string = "Geeks";
let paddedStr: string = str.padStart(10);

console.log(paddedStr);

Output:

Geeks

Example 2: Padding with Zeros

In this example, the padStart() method pads the string with zeros to reach the target length.

TypeScript
let str: string = "123";
let paddedStr: string = str.padStart(5, "0");

console.log(paddedStr);

Output:

00123

Next Article

Similar Reads