Here are padLeft
and padRight
implemented as simple JavaScript functions:
padLeft
JS
function padLeft(str, numChars = 4, char = ' ') {return (Array.from({ length: numChars }).fill(char).join('') + str).slice(-1 * numChars)}padLeft('Max', 8, ' ') // ' Max'padLeft('1', 4, '0') // '0001'
padRight
JS
function padRight(str, numChars = 4, char = ' ') {return (str + Array.from({ length: numChars }).fill(char).join('')).slice(0, numChars)}padRight('Max', 8, ' ') // 'Max 'padRight('1', 4, '0') // '1000'
How it works
The padLeft
function from above could also be written like this:
JS
function padLeft(str, numChars = 4, char = ' ') {// 1. Create an array of `numChars` length (Array.from)// 2. Fill it with `char` characters (Array.prototype.fill)// 3. Convert it to a string (Array.prototype.join)const characters = Array.from({ length: numChars }).fill(char).join('')// 4. Concat the characters and the stringconst charsAndString = characters + str// 5. Truncate the string from the right so it's at most// `numChars` characters longconst paddedString = charsAndString.slice(-1 * numChars)return paddedString}