Question 31
String padding
Some strings and numbers(money, date, timers etc) need to be represented in a particular format. Both padStart() & padEnd() methods introduced to pad a string with another string until the resulting string reaches the supplied length.
- padStart(): Using this method, padding is applied to the left or beginning side of the string.
For example, you may want to show only the last four digits of credit card number for security reasons,
const cardNumber = '01234567891234';
const lastFourDigits = cardNumber.slice(-4);
const maskedCardNumber = lastFourDigits.padStart(cardNumber.length, '*');
console.log(maskedCardNumber); // expected output: "**********1234"
- padEnd(): Using this method, padding is applied to the right or ending side of the string.
For example, the profile information padded for label and values as below
const label1 = "Name";
const label2 = "Phone Number";
const value1 = "John"
const value2 = "(222)-333-3456";
console.log((label1 + ': ').padEnd(20, ' ') + value1); // Name: John
console.log(label2 + ": " + value2); // Phone Number: (222)-333-3456