JavaScript example to add padding to the end of a string using padEnd

JavaScript example to add padding to the end of a string using padEnd:

In this post, we will learn how to add padding to the end of a string in JavaScript. JavaScript strings contains one method called padEnd which can be used to pad a string with a different string.

This method takes the final length and the string to use for padding.

In this post, we will learn how to use padEnd with an example.

Definition of padEnd:

padEnd is defined as like below:

padEnd(length)
padEnd(length, str)

Here,

  • length is the final length of the string after padded.
  • str is the string to pad. This is an optional value. If we don’t pass it, by default it takes blank spaces. It is truncated if the length is too long. If it is smaller than the length, then it will be repeated.

Example of padEnd:

Let’s take a look at the example below:

console.log('hello'.padEnd(10)) // 'hello     '
console.log('hello'.padEnd(10, '*')) // 'hello*****'
console.log('hello'.padEnd(10, 'hellllo')) // 'hellohelll'
console.log('hello'.padEnd(1)) // 'hello'

Here,

  • For the first one, it added blank spaces to the end of the string hello. 5 spaces are added to the end.
  • For the second one, it added 5 *. The final length is 10 and we are adding 5 * as the length of hello is 5.
  • For the third one, the string to pad is hellllo. It has 7 characters. To make the final string of length 10, it is truncated after 5 characters.
  • For the last one, we are passing 1 to padEnd and since it is smaller than the string length, it prints the complete string.

You might also like: