
ES8 introduced the padStart() and padEnd() methods that allow string padding.
The padStart() method pads a string with another string until it reaches a specified length. Its syntax is:
str.padStart(targetLength [, padString])
- targetLength: The length of the resulting string.
- padString (optional): The string to pad the original string with. If not specified, the string will be padded with spaces.
Example:
let str = 'hello';
let paddedStr = str.padStart(10, '-');
console.log(paddedStr); // '-----hello'
The padEnd() method works similarly but pads the end of the string instead of the beginning:
str.padEnd(targetLength [, padString])
Example:
let str = 'world';
let paddedStr = str.padEnd(10, '-');
console.log(paddedStr); // 'world-----'
Both methods are useful for formatting strings and aligning them within a fixed-width display.