Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you pad a string to a fixed length with spaces in JavaScript?

Calling . padStart(length) or . padEnd(length) returns a new string of the given length, with the start or end of the string padded with spaces. These padding functions do not modify the string that they are called on.

Is there a length function in JavaScript?

The length function in Javascript is used to return the length of an object. And since length is a property of an object it can be used on both arrays and strings. Although the syntax of the length function remains the same, bear in mind that the interpretation of length varies between arrays and strings.

Can you call the length of a string in JavaScript?

The length of a string in JavaScript can be found using the . length property. Since . length is a property it must be called through an instance of a string class.


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"


A faster method

If you are doing this repeatedly, for example to pad values in an array, and performance is a factor, the following approach can give you nearly a 100x advantage in speed (jsPerf) over other solution that are currently discussed on the inter webs. The basic idea is that you are providing the pad function with a fully padded empty string to use 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);
  }
}

For example, to zero pad a number to a length of 10 digits,

pad('0000000000',123,true);

To pad a string with whitespace, so the entire string is 255 characters,

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

Performance Test

See the jsPerf test here.

And this is faster than ES6 string.repeat by 2x as well, as shown by the revised JsPerf here

Please note that jsPerf is no longer online

Please note that the jsPerf site that we originally used to benchmark the various methods is no longer online. Unfortunately, this means we can't get to those test results. Sad but true.


String.prototype.padStart() and String.prototype.padEnd() are currently TC39 candidate proposals: see github.com/tc39/proposal-string-pad-start-end (only available in Firefox as of April 2016; a polyfill is available).


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 more readable.


Here's a recursive approach to it.

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

An example...

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

ECMAScript 2017 adds a padStart method to the String prototype. This method will pad a string with spaces to a given length. This method also takes an optional string that will be used instead of spaces for padding.

'abc'.padStart(10);         // "       abc"
'abc'.padStart(10, "foo");  // "foofoofabc"
'abc'.padStart(6,"123465"); // "123abc"
'abc'.padStart(8, "0");     // "00000abc"
'abc'.padStart(1);          // "abc"

A padEnd method was also added that works in the same manner.

For browser compatibility (and a useful polyfill) see this link.