Skip to content
Advertisement

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

I am in need of a JavaScript function which can take a value and pad it to a given length (I need spaces, but anything would do). I found this, but I have no idea what the heck it is doing and it doesn’t seem to work for me.

String.prototype.pad = function(l, s, t) {
  return s || (s = " "),
    (l -= this.length) > 0 ?
    (s = new Array(Math.ceil(l / s.length) + 1).join(s))
    .substr(0, t = !t ? l : t == 1 ?
      0 :
      Math.ceil(l / 2)) + this + s.substr(0, l - t) :
    this;
};



var s = "Jonas";
document.write(
  '<h2>S = '.bold(), s, "</h2>",
  'S.pad(20, "[]", 0) = '.bold(), s.pad(20, "[]", 0), "<br />",
  'S.pad(20, "[====]", 1) = '.bold(), s.pad(20, "[====]", 1), "<br />",
  'S.pad(20, "~", 2) = '.bold(), s.pad(20, "~", 2)
);

Advertisement

Answer

ECMAScript 2017 (ES8) 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 JavaScript host, String.padStart can be added as a polyfill.

Pre ES8

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”.

Advertisement