Coder Perfect

Is there a JavaScript function for padding a string to a specific length?

Problem

I’m looking for a JavaScript function that can pad a value to a specified length (I need spaces, but anything would do). I came upon this, but I have no idea what it’s doing and it doesn’t appear to work for me.

Asked by Anthony Potts

Solution #1

String.padStart (together with String.padEnd) were implemented in EcmaScript 2017 specifically for this purpose:

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

String.padStart can be used as a polyfill if the JS host doesn’t provide it.

This is the solution I found, and it’s a lot easier for me:

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 it was here that I added a new feature to the string object:

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

Use this as an example:

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;
    });
};

A time in the format “15:30” will be returned.

Answered by Samuel

Solution #2

If you’re doing this frequently, say to pad values in an array, and speed is a concern, the following approach can give you a nearly 100x speed advantage (jsPerf) over alternative solutions currently being discussed on the internet. The basic notion is that you pass a fully padded empty string to the pad function to utilize as a buffer. The pad function just appends to string to be added to this pre-padded string (one string concat) and then slices or trims the result to the desired length.

function pad(pad, str, padLeft) {
  if (typeof str === 'undefined') 
    return pad;
  if (padLeft) {
    return (pad + str).slice(-pad.length);
  } else {
    return (str + pad).substring(0, pad.length);
  }
}

To zero pad an integer to a length of 10 digits, for example,

pad('0000000000',123,true);

To make a string 255 characters long, add whitespace at the beginning and end.

var padding = Array(256).join(' '), // make a string of 255 spaces
pad(padding,123,true);

The jsPerf test can be found here.

This is also faster than the ES6 string. As evidenced by the revised JsPerf here, repeat by 2x.

Please note that the jsPerf website that we used to compare the different approaches is no longer available. Unfortunately, this means we won’t be able to see the outcomes of the tests. Regrettably, this is correct.

Answered by Shyam Habarakada

Solution #3

TC39 candidate proposals for String.prototype.padStart() and String.prototype.padEnd() are available at github.com/tc39/proposal-string-pad-start-end. (As of April 2016, it’s only supported in Firefox; a polyfill is available).

Answered by ChrisV

Solution #4

http://www.webtoolkit.info/javascript_pad.html

/**
*
*  Javascript string pad
*  http://www.webtoolkit.info/
*
**/

var STR_PAD_LEFT = 1;
var STR_PAD_RIGHT = 2;
var STR_PAD_BOTH = 3;

function pad(str, len, pad, dir) {

    if (typeof(len) == "undefined") { var len = 0; }
    if (typeof(pad) == "undefined") { var pad = ' '; }
    if (typeof(dir) == "undefined") { var dir = STR_PAD_RIGHT; }

    if (len + 1 >= str.length) {

        switch (dir){

            case STR_PAD_LEFT:
                str = Array(len + 1 - str.length).join(pad) + str;
            break;

            case STR_PAD_BOTH:
                var padlen = len - str.length;
                var right = Math.ceil( padlen / 2 );
                var left = padlen - right;
                str = Array(left+1).join(pad) + str + Array(right+1).join(pad);
            break;

            default:
                str = str + Array(len + 1 - str.length).join(pad);
            break;

        } // switch

    }

    return str;

}

It’s a lot easier to read now.

Answered by David

Solution #5

Here’s how to do things in a recursive manner.

function pad(width, string, padding) { 
  return (width <= string.length) ? string : pad(width, padding + string, padding)
}

An example…

pad(5, 'hi', '0')
=> "000hi"

Answered by hypno7oad

Post is based on https://stackoverflow.com/questions/2686855/is-there-a-javascript-function-that-can-pad-a-string-to-get-to-a-determined-leng