Related Tags

javascript
communitycreator

# How to pad a string in JavaScript

Programming Bytes

The padStart and padEnd methods pad a string with another string until the resulting string reaches the given length.

• padStart pads the padString to the start of the source string.
• padEnd pads the padString to the end of the source string.

Both the padStart and padEnd methods take two arguments:

• resultStringLength – the length of the resulting string on padding. If the value is less than sourceString.length, then the sourceString is returned.
• padString – the string to be padded with the sourceString. If the padString is too long to stay within the resultStringLength, then the padString is truncated from the end. The default value of the padString is ' ' (single space).

Take a look at the code below:

let loading = 'loading';



## Examples

### 1. Passing undefined as the padString

When we don’t pass in a padString, then the default padString (' ') will be used to pad.

let loading = 'loading';

console.log("Adding pad at beginning", loading.padStart(20, undefined) );

### 2. Passing an empty string as the padString

When we pass an empty string ('') as the padString, then the padding will not happen and the sourceString will be returned.

let loading = 'loading';

console.log("Padding with 20 at beginning",loading.padStart(20, ''));

### 3. Passing a padString larger than the targetLength

If the padString is too long to stay within the resultStringLength, it will be truncated from the end of the padString. Suppose we have:

• a sourceString with length $5$
• a padString with length $20$
• a target with length $10$

Then, from the padString, we will take a substring of the first $5$ characters and pad to the sourceString.

let str = 'five';

console.log( str.padStart(10, " large pad String") ); // largefive

### 4. Passing other data types as a padString

When we pass a padString as other than a string or undefined, then it will be converted using toString.

console.log("Padding other data tyypes ")

// number - (num).toString() will be internally called

// boolean -- (bool_val).toString() will be internally called

let array = [1,2,3];
// array.toString() will be internally called , which returns 1,2,3

let obj = {name : "JS"};
console.log( loading.padStart(22, obj) );

RELATED TAGS

javascript
communitycreator

CONTRIBUTOR

Programming Bytes
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time