Here are padLeft
and padRight
implemented as simple JavaScript functions:
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'
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'
The padLeft
function from above could also be written like this:
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}
Hi, I’m Max! I'm a fullstack JavaScript developer living in Berlin.
When I’m not working on one of my personal projects, writing blog posts or making YouTube videos, I help my clients bring their ideas to life as a freelance web developer.
If you need help on a project, please reach out and let's work together.
To stay updated with new blog posts, follow me on Twitter or subscribe to my RSS feed.