This post will discuss how to apply padding to the start or end of a string in JavaScript.

There are several ways to apply a padding to a string in JavaScript, depending on where and how we want to add the padding. Padding is the process of adding extra characters to a string to make it longer or align it with a certain format. Here are some of the most common and easy-to-use functions for applying padding to a string in JavaScript:

1. Using padStart() function

The padStart() function is a modern and simple way of applying padding to a string. This function pads a string from the start with another string (multiple times, if needed) until the resulting string reaches a given length. For example, to add 5 spaces to the start of the string "Hello", we can use:

Download  Run Code

2. Using padEnd() function

Similar to the padStart() function, padEnd() is also a modern and simple way of applying padding to a string. This function pads a string with another string (multiple times, if needed) until the resulting string reaches the given target length. The padding is applied from the end of the current string. For example, to add 5 spaces to the end of the string "Hello", we can use:

Download  Run Code

3. Using repeat() function

The repeat() function is a useful way of creating a padding string with a fixed character or substring. This function returns a new string that contains the given string repeated a specified number of times. We can use this function to create a padding string and then concatenate it with the original string. For example, to add 5 spaces to the start of the string "Hello", we can use:

Download  Run Code

4. Using Template literals

These are special strings that allow embedded expressions and multi-line strings. We can use template literals to add padding to a string by enclosing both the string and the padding in backticks (` `), and using the dollar sign ($) and curly braces ({}) to indicate an expression. For example, if we want to add padding of x’s to the end of the string "5" until it reaches the length 4, we can write:

Download  Run Code

That’s all about applying padding to the start or end of a string in JavaScript.