How to pad a string in JavaScript
The padStart and padEnd methods pad a string with another string until the resulting string reaches the given length.
padStartpads the padString to the start of the source string.padEndpads 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 thansourceString.length, then the sourceString is returned.padString– the string to be padded with the sourceString. If the padString is too long to stay within theresultStringLength, 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';console.log ( "Padding . at end " ,loading.padEnd(20, '.') ); // "loading............."console.log ( "Padding # at start ", loading.padStart(20, '#') ); // "#############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 end", loading.padEnd(20) , ".");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("Adding empty string will not pad the string ")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
- a padString with length
- a target with length
Then, from the padString, we will take a substring of the first characters and pad to the sourceString.
let str = 'five';console.log( str.padEnd(6, " large pad String") ); // "five l"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 ")let loading = "loading";console.log("\n---------------\nPadding a number ")// number - (num).toString() will be internally calledconsole.log( loading.padStart(10, 4) );console.log("\n---------------\nPadding a boolean ")// boolean -- (bool_val).toString() will be internally calledconsole.log( loading.padStart(11, true) );console.log("\n---------------\nPadding a array")let array = [1,2,3];// array.toString() will be internally called , which returns 1,2,3console.log( loading.padStart(10, array) );console.log("\n---------------\nPadding a object");let obj = {name : "JS"};console.log( loading.padStart(22, obj) );