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

EcmaScript 2017 added String.padStart (along with String.padEnd) for just this purpose:

"Jonas".padStart(10); // Default pad string is a space
"42".padStart(6, "0"); // Pad with "0"
"*".padStart(8, "-/|\\"); // produces '-/|\\-/|*'

If not present in the JS host, String.padStart can be added as a polyfill.

Pre ES-2017

I found this solution here and this is for me much much simpler:

var n = 123

String("00000" + n).slice(-5); // returns 00123
("00000" + n).slice(-5); // returns 00123
("     " + n).slice(-5); // returns "  123" (with two spaces)

And here I made an extension to the string object:

String.prototype.paddingLeft = function (paddingValue) {
   return String(paddingValue + this).slice(-paddingValue.length);
};

An example to use it:

function getFormattedTime(date) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  
  hours = hours.toString().paddingLeft("00");
  minutes = minutes.toString().paddingLeft("00");
  
  return "{0}:{1}".format(hours, minutes);
};

String.prototype.format = function () {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function (match, number) {
        return typeof args[number] != 'undefined' ? args[number] : match;
    });
};

This will return a time in the format “15:30”

Leave a Comment