Explain Codes LogoExplain Codes Logo

Is there a JavaScript function that can pad a string to get to a determined length?

javascript
string-manipulation
polyfill
performance-optimization
Nikita BarsukovbyNikita Barsukov·Aug 23, 2024
TLDR

In JavaScript, .padStart() and .padEnd() methods are at your disposal to pad strings to a specified length with a specified character. Here's a handy illustration:

let str = "5"; str.padStart(3, "0"); // "005" str.padEnd(3, "0"); // "500"

While padStart() pads at the start of the string, padEnd() does the end. If these methods aren't supported in your environment, try whipping up a polyfill, or you may opt for methods like String.prototype.paddingLeft.

Craftier alternatives to padStart() and padEnd()

Making a polyfill

For those adventurous with older browsers that do not support padStart() or padEnd(), a polyfill paves the way. It's nothing but a snippet that furnishes those functionalities. Check out this DIY polyfill for padStart():

// Brace yourselves, polyfill is coming! if (!String.prototype.padStart) { String.prototype.padStart = function(targetLength, padString) { targetLength = targetLength >> 0; // Nothing gets past this line without being a number padString = String(padString || ' '); // Default padding string is a space ' ' if (this.length >= targetLength) { return String(this); } targetLength = targetLength - this.length; // Let's double the padding string to cover all possible cases while (padString.length < targetLength) { padString += padString; } // Our very own version of padStart is ready for action! return padString.slice(0, targetLength) + String(this); }; }

Padding using string concatenation

String concatenation is another card up your sleeve for padding strings. You get full control over the padding process:

// Function to add some extra 'character' to our string function padLeft(str, targetLength, padChar = ' ') { let padding = new Array(targetLength).join(padChar); // Bon Appétit! Enjoy the 'souped-up' string! return padding.substr(0, targetLength - str.length) + str; }

Pre-padded strings ft. slice

For the performance hogs out there, use a pre-padded string coupled with slice to achieve rapid-fire string padding:

let padChar = '0'; let maxLength = 5; // A string as padded and ready as you first thing on a Monday morning let prePaddedString = new Array(maxLength + 1).join(padChar); function leftPad(str) { // Classic example of 'work smart, not hard' return (prePaddedString + str).slice(-maxLength); }

Leveling up your string padding game

Recursion to the rescue

A recursive approach to padding can considerably streamline the logic, although it might not always be your best bet in terms of performance:

function recursivePad(str, targetLength, padChar = ' ') { // I'll be back, unless I'm long enough already! if (str.length >= targetLength) return str; return recursivePad(padChar + str, targetLength, padChar); }

Dynamic padding based on conditions

When dealing with ever-changing data, you might be required to perform different padding based on various conditions:

function dynamicPad(str, targetLength, padChar = ' ', condition) { let padding = condition ? padChar.repeat(targetLength) : ''; // One string to rule them all! return padding + str; }

Predefined strings for common scenarios

Predefined strings can speed up the game if you're tackling a lot of common padding scenarios:

const ZERO_PADDED = '00000'; const SPACE_PADDED = ' '; function padWithPredefined(str, type) { switch (type) { case 'zeros': return (ZERO_PADDED + str).slice(-5); case 'spaces': return (SPACE_PADDED + str).slice(-5); default: return str; // Anything else and I'll just chill! } }