String.prototype.padStartLoading saved progress…

String.prototype.padStart

String.prototype.padStart pads a string from the left until it reaches a target length, so shorter strings line up to a fixed width. It's how you zero-pad a number ('5''005'), right-align a column, or format a clock digit.

Implement stringPadStart(str, targetLength, padString). Prepend copies of padString (default ' ') until the result is targetLength characters long. If str is already that long or longer, return it unchanged. If padString has more than one character, repeat and then truncate it so the result is exactly targetLength — never longer.

Signature

function stringPadStart(str, targetLength, padString = ' ') {
  // returns str padded on the left to targetLength using padString;
  // unchanged if str is already long enough.
}

Examples

stringPadStart('5', 3, '0');   // '005'
stringPadStart('5', 3);        // '  5'  — default pad is a space
stringPadStart('abc', 2, '0'); // 'abc'  — already long enough, unchanged
stringPadStart('1', 4, 'ab');  // 'aba1' — multi-char pad truncated to fit

Notes

  • Left side — padding is prepended; the original string ends up on the right.
  • Already long enough — if str.length >= targetLength, return str untouched (no truncation of str).
  • Multi-char pad truncates — a padString longer than one character is repeated, then cut so the final length is exactly targetLength.
  • Empty pad — a padString of '' can't fill anything, so return str unchanged.
  • padEnd is the mirror — same logic, but the padding goes on the right.
Loading editor…