Padding a string

The padStart and padEnd function continuously append characters to a string until it reaches a certain length. These functions are especially useful when displaying information in tables or aligning values in console output.

Loading TypeScript...

If the character to append is not specified, it is assumed to be a space character. The resulting string will be the exact specified length, which means a padding string that does not evenly fit the remaining space will be truncated.

Loading TypeScript...

Notice that if the original string is larger than the desired padding length, it won't be truncated.

Loading TypeScript...

Padding is often useful when converting numbers to a fixed width. Consider the function below that converts an RGB value to a hex code, which would otherwise fail to output a correct hex code if either red, green, or blue are less than 16.

Loading TypeScript...

Was this page helpful?