Max Schmitt

September 5 2021

Padding Strings in JavaScript: padLeft & padRight

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 string
const charsAndString = characters + str
// 5. Truncate the string from the right so it's at most
// `numChars` characters long
const paddedString = charsAndString.slice(-1 * numChars)
return paddedString
}