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

44

337

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)
);
Incubation answered 21/4, 2010 at 21:59 Comment(5)
"Jonas".padStart(7, " ") developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Lanthorn
This answer with the standard, now-built-in padStart and padEnd should be the accepted one now. (Present in all major browsers; IE11 or even earlier can be polyfilled.)Pandit
@T.J.Crowder sorry to bother you, I use node.js on a server (like, a ubuntu server) and I don't know how to use .padEnd() etc; they are unevailable when I try. Can you help? :O :O TY :)Gribble
@Gribble - Sounds like you're using a really old version of Node.js. padEnd was added in ES2017, so Node.js has had it for over six years. The oldest version I have handy to check is v10.20.1, and even it has padEnd. Try node --version to see what version you have. The current LTS is v20.11.1, cutting edge is v21.6.2.Pandit
@T.J.Crowder you're amazing. Your info was key. Also, as a Swift programmer :) I realized I was foolishly using .padEnd on an undefined (I failed to read the clear error message). Thank you so much !!!!!!!!!Gribble
B
622

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

Bankbook answered 7/2, 2013 at 20:27 Comment(7)
Easily the most readable and concise approach I've found; simple enough that I generally wouldn't even bother with the prototype extension (at least for only a few uses in an app). Well done.Used
Be aware, this solution will shorten strings that are longer than the slice argument (i.e. 5 chars here).Anecdotal
Great solution. However, as Denis mentions this will truncate the number when greater than the paddingValue. Can easily fix this with slicing the greater of the two. E.g. return String(paddingValue + this).slice(-1 * Math.max(this.length, paddingValue.length)); };Agonist
Hi Yaniv. You have a very good suggestion to modify the algorithm. However, in my case, the requirements always precede this problem because when I try to format something, I always have a minimum of specifications about the value that I have to treat and in this case, the specifications will correct this problem. As example, if I have a phone number to format and I only handle phone in Canada, I will validate that the phone number have 10 characters before formatting it. In any cases, your solution is great too. :)Bankbook
If you are doing this a lot (e.g. padding a long list of values in a list of some sort on your page or other application) also see the answer with a A faster method at #2687355Actinology
This badly needs to be updated to use the JS String libs String.padStart() and String.padEnd() for left/right padding.Feuillant
String.padStart() and String.padEnd() are great but as a note they're not supported by IE11.Boracite
A
132

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.

Actinology answered 24/6, 2014 at 23:51 Comment(5)
+1 Part of my issue with StackOverflow is the inability for moderators to change votes based off answers that are clearly superior. This is one of those cases.Dedicate
As someone else proved out in a later jsPerf (links added above), this approach is ~ 2x faster than the ES6 string.repeat method. So if you are doing a lot of string padding, definitely try this.Actinology
I am confused by Jason's comment – how is this answer different from the accepted?Chico
I looked at your jsPerf. Those tests are for your function and something that uses a while() loop, which no other high-rated answer uses. I'm not sure that means it's faster?Cantatrice
My only observation with this approach is, if the actual str length is grater than the pad length, then the output will be chopped at the end. Meaning that str will be returned to the length of pad. This may not be the intended or expected behavior.Somewise
C
66

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

Chickenhearted answered 8/4, 2016 at 15:34 Comment(4)
Supported by all (modern) browsers now: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Timmerman
For the lazy: myString.padStart(padLength [, padString]) and myString.padEnd(padLength [, padString])Cerf
Please add some example usage, now that this has been supported by all modern browsers. This should be encouraged.Parmenter
Holy crap, how have I not heard of this until today?? This should be the accepted answer.Damales
P
47

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.

Parcheesi answered 21/4, 2010 at 22:2 Comment(1)
Does not seem to work when pad is a space: pad("hello", 20) = "hello "Sanctify
R
46

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"
Roe answered 27/3, 2013 at 13:49 Comment(8)
there's also a recursive definition of integer multiplication... always remember there's a 'curse' in recursive...Neodarwinism
There's also narwhals and a drunk guy down the street, but neither are relevant. The curse of recursion only applies when a programmer doesn't know when its appropriate.Roe
"The curse of recursion only applies when a programmer doesn't know when its appropriate" Or when they don't realize it is inappropriate. Such as for a simple string pad function.Condone
This is pretty elegant and worked perfectly for my use case. If you need to pad spaces to align text, just throw in the length of the longest string =)Unbeliever
It is elegant, but it also creates a new string on each iteration of the function. This function is O(n) while the most popular solution by @Bankbook is O(1). Both are elegant, but one is vastly more efficient. That said, it's a neat approach, and might be even faster in a different language.Charla
Add 'string = string.toString();' to the function for when you pass it an integer.Defluxion
imho, that should be the chosen answerJohanna
You could eaisly avoid recursion by using while. And make it faster by saving padded string... E.g.: gist.github.com/Eccenux/52062de47b11cd79ffb0f2c7995dc0f3Bautram
K
44

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.

Kasey answered 22/9, 2017 at 22:52 Comment(1)
Best answer HERE for nowadays! 2019!Friederike
P
23

Using the ECMAScript 6 method String#repeat, a pad function is as simple as:

String.prototype.padLeft = function(char, length) {
    return char.repeat(Math.max(0, length - this.length)) + this;
}

String#repeat is currently supported in Firefox and Chrome only. for other implementation, one might consider the following simple polyfill:

String.prototype.repeat = String.prototype.repeat || function(n){
    return n<=1 ? this : (this + this.repeat(n-1));
}
Peal answered 18/12, 2014 at 12:57 Comment(1)
For those working in Node.js, String.repeat is also supported there.Movie
E
17

Using the ECMAScript 6 method String#repeat and Arrow functions, a pad function is as simple as:

var leftPad = (s, c, n) => c.repeat(n - s.length) + s;
leftPad("foo", "0", 5); //returns "00foo"

jsfiddle

edit: suggestion from the comments:

const leftPad = (s, c, n) => n - s.length > 0 ? c.repeat(n - s.length) + s : s;

this way, it wont throw an error when s.lengthis greater than n

edit2: suggestion from the comments:

const leftPad = (s, c, n) =>{ s = s.toString(); c = c.toString(); return s.length > n ? s : c.repeat(n - s.length) + s; }

this way, you can use the function for strings and non-strings alike.

Erlandson answered 27/3, 2016 at 12:37 Comment(4)
This is nice, but if s.length is greater than n it will throw. Suggest: let leftPad = (s, c, n) => n - s.length > 0 ? c.repeat(n - s.length) + s : s;Coessential
it doesn't work for non-strings. As in leftPad(12, ' ', 5) . While I know strictly speaking that might be ok it's probably one of the most common use cases (padding numbers). Maybe function leftPad(s, c, n) { s = s.toString(); return s.length > len ? s : c.repeat(n - s.length) + s; }. Using function means leftPad can be at the bottom of the file. Otherwise you should arguably use const not var nor let.Weave
@Weave thanks for this suggestion, but what is your variable len?Erlandson
Doh, len should be nWeave
T
14

The key trick in both those solutions is to create an array instance with a given size (one more than the desired length), and then to immediately call the join() method to make a string. The join() method is passed the padding string (spaces probably). Since the array is empty, the empty cells will be rendered as empty strings during the process of joining the array into one result string, and only the padding will remain. It's a really nice technique.

Timmytimocracy answered 21/4, 2010 at 22:5 Comment(0)
G
10

Pad with default values

I noticed that I mostly need the padLeft for time conversion / number padding.

So I wrote this function:

function padL(a, b, c) { // string/number, length=2, char=0
  return (new Array(b || 2).join(c || 0) + a).slice(-b)
}

This simple function supports Number or String as input.

The default pad is two characters.

The default char is 0.

So I can simply write:

padL(1);
// 01

If I add the second argument (pad width):

padL(1, 3);
// 001

The third parameter (pad character)

padL('zzz', 10, 'x');
// xxxxxxxzzz

@BananaAcid: If you pass a undefined value or a 0 length string, you get 0undefined, so:

As suggested

function padL(a, b, c) { // string/number, length=2, char=0
  return (new Array((b || 1) + 1).join(c || 0) + (a || '')).slice(-(b || 2))
}

But this can also be achieved in a shorter way.

function padL(a, b, c) { // string/number, length=2, char=0
  return (new Array(b || 2).join(c || 0) + (a || c || 0)).slice(-b)
}

It also works with:

padL(0)
padL(NaN)
padL('')
padL(undefined)
padL(false)

And if you want to be able to pad in both ways:

function pad(a, b, c, d) { // string/number, length=2, char=0, 0/false=Left-1/true=Right
  return a = (a || c || 0), c = new Array(b || 2).join(c || 0), d ? (a + c).slice(0, b) : (c + a).slice(-b)
}

which can be written in a shorter way without using slice.

function pad(a, b, c, d) {
  return a = (a || c || 0) + '', b = new Array((++b || 3) - a.length).join(c || 0), d ? a+b : b+a
}
/*

Usage:

pad(
 input // (int or string) or undefined, NaN, false, empty string
       // default:0 or PadCharacter
 // Optional
 ,PadLength // (int) default:2
 ,PadCharacter // (string or int) default:'0'
 ,PadDirection // (bolean) default:0 (padLeft) - (true or 1) is padRight
)

*/

Now if you try to pad 'averylongword' with 2... that’s not my problem.


I said that I would give you a tip.

Most of the time, if you pad, you do it for the same value N times.

Using any type of function inside a loop slows down the loop!!!

So if you just want to pad left some numbers inside a long list, don't use functions to do this simple thing.

Use something like this:

var arrayOfNumbers = [1, 2, 3, 4, 5, 6, 7],
    paddedArray = [],
    len = arrayOfNumbers.length;
while(len--) {
  paddedArray[len] = ('0000' + arrayOfNumbers[len]).slice(-4);
}

If you don't know how the maximum padding size based on the numbers inside the array.

var arrayOfNumbers = [1, 2, 3, 4, 5, 6, 7, 49095],
    paddedArray = [],
    len = arrayOfNumbers.length;

// Search the highest number
var arrayMax = Function.prototype.apply.bind(Math.max, null),
// Get that string length
padSize = (arrayMax(arrayOfNumbers) + '').length,
// Create a Padding string
padStr = new Array(padSize).join(0);
// And after you have all this static values cached start the loop.
while(len--) {
  paddedArray[len] = (padStr + arrayOfNumbers[len]).slice(-padSize); // substr(-padSize)
}
console.log(paddedArray);

/*
0: "00001"
1: "00002"
2: "00003"
3: "00004"
4: "00005"
5: "00006"
6: "00007"
7: "49095"
*/
Gisser answered 25/1, 2014 at 9:45 Comment(2)
Very nice! Came up with the same result, just as a note: this concats the string to the maximum length given and an empty string will be one char too short and undefined str will result in 'undefined' beeing used as well as splice could throw an error -- combined. return (new Array((b||1)+1).join(c||0)+(a||'')).slice(-(b||2)). And as always: you guys out there, do not just copy code you do not understand.Diakinesis
(new Array(b||2).join(c||0)+(a||c||0)).slice(-b)...shorterGisser
A
10

Taking up Samuel's ideas, upward here. And remember an old SQL script, I tried with this:

a=1234;
'0000'.slice(a.toString().length)+a;

It works in all the cases I could imagine:

a=     1 result  0001
a=    12 result  0012
a=   123 result  0123
a=  1234 result  1234
a= 12345 result 12345
a=  '12' result  0012
April answered 23/3, 2015 at 17:46 Comment(1)
Yes works fine with my example of: HHMM = '00'.slice((dif/60>>0).toString().length)+(dif/60>>0) + ":" + '00'.slice((dif%60).toString().length)+(dif%60)Prynne
B
6

Here is a build in method you can use -

str1.padStart(2, '0')
Burn answered 9/3, 2021 at 11:41 Comment(1)
yeah, 11 years ago there wasn't one but your answer is what is in the comment of my question.Incubation
G
5

padding string has been inplemented in new javascript version.

str.padStart(targetLength [, padString])

https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/String/padStart

If you want your own function check this example:

const myString = 'Welcome to my house';
String.prototype.padLeft = function(times = 0, str = ' ') {
    return (Array(times).join(str) + this);
}
console.log(myString.padLeft(12, ':'));
//:::::::::::Welcome to my house
Gaddy answered 6/3, 2018 at 21:40 Comment(2)
This answer has been mentioned by multiple other answers so it's a duplicate that adds no new information. Please search before answer.Parmenter
This one is the first one with the full signature. And it must be the only answer as of today.Isagogics
P
4

Here's a simple function that I use.

var pad=function(num,field){
    var n = '' + num;
    var w = n.length;
    var l = field.length;
    var pad = w < l ? l-w : 0;
    return field.substr(0,pad) + n;
};

For example:

pad    (20,'     ');    //   20
pad   (321,'     ');    //  321
pad (12345,'     ');    //12345
pad (   15,'00000');    //00015
pad (  999,'*****');    //**999
pad ('cat','_____');    //__cat  
Poilu answered 28/7, 2013 at 0:11 Comment(0)
M
4

A short way:

(x=>(new Array(int-x.length+1)).join(char)+x)(String)

Example:

(x=>(new Array(6-x.length+1)).join("0")+x)("1234")

return: "001234"

Mathis answered 19/9, 2017 at 16:2 Comment(1)
maybe String.prototype.padStart() should be easier.Partlow
G
3

ES7 is just drafts and proposals right now, but if you wanted to track compatibility with the specification, your pad functions need:

  1. Multi-character pad support.
  2. Don't truncate the input string
  3. Pad defaults to space

From my polyfill library, but apply your own due diligence for prototype extensions.

// Tests
'hello'.lpad(4) === 'hello'
'hello'.rpad(4) === 'hello'
'hello'.lpad(10) === '     hello'
'hello'.rpad(10) === 'hello     '
'hello'.lpad(10, '1234') === '41234hello'
'hello'.rpad(10, '1234') === 'hello12341'

String.prototype.lpad || (String.prototype.lpad = function(length, pad)
{
    if(length < this.length)
        return this;

    pad = pad || ' ';
    let str = this;

    while(str.length < length)
    {
        str = pad + str;
    }

    return str.substr( -length );
});

String.prototype.rpad || (String.prototype.rpad = function(length, pad)
{
    if(length < this.length)
        return this;

    pad = pad || ' ';
    let str = this;

    while(str.length < length)
    {
        str += pad;
    }

    return str.substr(0, length);
});
Generalization answered 12/6, 2015 at 17:23 Comment(0)
P
3

Here is a simple answer in basically one line of code.

var value = 35 // the numerical value
var x = 5 // the minimum length of the string

var padded = ("00000" + value).substr(-x);

Make sure the number of characters in you padding, zeros here, is at least as many as your intended minimum length. So really, to put it into one line, to get a result of "00035" in this case is:

var padded = ("00000" + 35).substr(-5);
Predictor answered 14/8, 2015 at 18:34 Comment(0)
M
2

Array manipulations are really slow compared to simple string concat. Of course, benchmark for your use case.

function(string, length, pad_char, append) {
    string = string.toString();
    length = parseInt(length) || 1;
    pad_char = pad_char || ' ';

    while (string.length < length) {
        string = append ? string+pad_char : pad_char+string;
    }
    return string;
};
Monocarpic answered 20/4, 2013 at 16:36 Comment(0)
C
2

A variant of @Daniel LaFavers' answer.

var mask = function (background, foreground) {
  bg = (new String(background));
  fg = (new String(foreground));
  bgl = bg.length;
  fgl = fg.length;
  bgs = bg.substring(0, Math.max(0, bgl - fgl));
  fgs = fg.substring(Math.max(0, fgl - bgl));
  return bgs + fgs;
};

For example:

mask('00000', 11  );   // '00011'
mask('00011','00' );   // '00000'
mask( 2     , 3   );   // '3'
mask('0'    ,'111');   // '1'
mask('fork' ,'***');   // 'f***'
mask('_____','dog');   // '__dog'
Charlacharlady answered 30/11, 2013 at 23:43 Comment(0)
C
2

It's 2014, and I suggest a JavaScript string-padding function. Ha!

Bare-bones: right-pad with spaces

function pad (str, length) {
    var padding = (new Array(Math.max(length - str.length + 1, 0))).join(" ");
    return str + padding;
}

Fancy: pad with options

/**
 * @param {*}       str                         Input string, or any other type (will be converted to string)
 * @param {number}  length                      Desired length to pad the string to
 * @param {Object}  [opts]
 * @param {string}  [opts.padWith=" "]          Character to use for padding
 * @param {boolean} [opts.padLeft=false]        Whether to pad on the left
 * @param {boolean} [opts.collapseEmpty=false]  Whether to return an empty string if the input was empty
 * @returns {string}
 */
function pad(str, length, opts) {
    var padding = (new Array(Math.max(length - (str + "").length + 1, 0))).join(opts && opts.padWith || " "),
        collapse = opts && opts.collapseEmpty && !(str + "").length;
    return collapse ? "" : opts && opts.padLeft ? padding + str : str + padding;
}

Usage (fancy):

pad("123", 5);
// Returns "123  "

pad(123, 5);
// Returns "123  " - non-string input

pad("123", 5, { padWith: "0", padLeft: true });
// Returns "00123"

pad("", 5);
// Returns "     "

pad("", 5, { collapseEmpty: true });
// Returns ""

pad("1234567", 5);
// Returns "1234567"
Cuneal answered 26/11, 2014 at 22:26 Comment(0)
M
2

If you don't mind including a utility library, lodash library has _.pad, _.padLeft and _.padRight functions.

Motile answered 26/10, 2015 at 13:17 Comment(0)
I
2

I think its better to avoid recursion because its costly.

function padLeft(str,size,padwith) {
	if(size <= str.length) {
        // not padding is required.
		return str;
	} else {
        // 1- take array of size equal to number of padding char + 1. suppose if string is 55 and we want 00055 it means we have 3 padding char so array size should be 3 + 1 (+1 will explain below)
        // 2- now join this array with provided padding char (padwith) or default one ('0'). so it will produce '000'
        // 3- now append '000' with orginal string (str = 55), will produce 00055

        // why +1 in size of array? 
        // it is a trick, that we are joining an array of empty element with '0' (in our case)
        // if we want to join items with '0' then we should have at least 2 items in the array to get joined (array with single item doesn't need to get joined).
        // <item>0<item>0<item>0<item> to get 3 zero we need 4 (3+1) items in array   
		return Array(size-str.length+1).join(padwith||'0')+str
	}
}

alert(padLeft("59",5) + "\n" +
     padLeft("659",5) + "\n" +
     padLeft("5919",5) + "\n" +
     padLeft("59879",5) + "\n" +
     padLeft("5437899",5));
Inconsequent answered 4/12, 2015 at 7:45 Comment(0)
L
1
/**************************************************************************************************
Pad a string to pad_length fillig it with pad_char.
By default the function performs a left pad, unless pad_right is set to true.

If the value of pad_length is negative, less than, or equal to the length of the input string, no padding takes place.
**************************************************************************************************/
if(!String.prototype.pad)
String.prototype.pad = function(pad_char, pad_length, pad_right) 
{
   var result = this;
   if( (typeof pad_char === 'string') && (pad_char.length === 1) && (pad_length > this.length) )
   {
      var padding = new Array(pad_length - this.length + 1).join(pad_char); //thanks to https://mcmap.net/q/10228/-repeat-string-javascript-duplicate/2433358#2433358
      result = (pad_right ? result + padding : padding + result);
   }
   return result;
}

And then you can do:

alert( "3".pad("0", 3) ); //shows "003"
alert( "hi".pad(" ", 3) ); //shows " hi"
alert( "hi".pad(" ", 3, true) ); //shows "hi "
Lava answered 12/6, 2013 at 15:42 Comment(1)
Don't mess with the prototypes!Southsoutheast
I
1

Here is a JavaScript function that adds a specified number of paddings with a custom symbol. The function takes three parameters.

padMe --> string or number to left pad
pads  --> number of pads
padSymble --> custom symbol, default is "0"
function leftPad(padMe, pads, padSymble) {
    if(typeof padMe === "undefined") {
        padMe = "";
    }
    if (typeof pads === "undefined") {
        pads = 0;
    }
    if (typeof padSymble === "undefined") {
        padSymble = "0";
    }

    var symble = "";
    var result = [];
    for(var i=0; i < pads; i++) {
       symble += padSymble;
    }
    var length = symble.length - padMe.toString().length;
    result = symble.substring(0, length);
    return result.concat(padMe.toString());
}

Here are some results:

> leftPad(1)
"1"

> leftPad(1, 4)
"0001"

> leftPad(1, 4, "0")
"0001"

> leftPad(1, 4, "@")
"@@@1"
Into answered 7/1, 2014 at 1:26 Comment(0)
P
1

If you just want a very simple hacky one-liner to pad, just make a string of the desired padding character of the desired max padding length and then substring it to the length of what you want to pad.

Example: padding the string store in e with spaces to 25 characters long.

var e = "hello"; e = e + "                         ".substring(e.length)

Result: "hello "

If you want to do the same with a number as input just call .toString() on it before.

Prochronism answered 1/4, 2014 at 12:27 Comment(2)
This is actually pretty neat, not as a general purpose function - but I could see this as a valid hack in some contexts to save a loop.Adelric
Interesting idea. @Adelric To use it as a general purpose function, you could use Array(n).join(c) to make the padding length and padding character configurable, e.g. Array(26).join(' ').Abrupt
A
1

Yet another take at with combination of a couple of solutions:

/**
 * pad string on left
 * @param {number} number of digits to pad, default is 2
 * @param {string} string to use for padding, default is '0' *
 * @returns {string} padded string
 */
String.prototype.paddingLeft = function (b, c) {
    if (this.length > (b||2))
        return this + '';
  return (this || c || 0) + '', b = new Array((++b || 3) - this.length).join(c || 0), b + this
};

/**
 * pad string on right
 * @param {number} number of digits to pad, default is 2
 * @param {string} string to use for padding, default is '0' *
 * @returns {string} padded string
 */
String.prototype.paddingRight = function (b, c) {
  if (this.length > (b||2))
        return this + '';
  return (this||c||0) + '', b = new Array((++b || 3) - this.length).join(c || 0), this + b
};
Aboriginal answered 22/1, 2015 at 19:53 Comment(0)
F
1

A friend asked about using a JavaScript function to pad left. It turned into a little bit of an endeavor between some of us in chat to code golf it. This was the result:

function l(p,t,v){
    v+="";return v.length>=t?v:l(p,t,p+v); 
}

It ensures that the value to be padded is a string, and then if it isn't the length of the total desired length it will pad it once and then recurse. Here is what it looks like with more logical naming and structure

function padLeft(pad, totalLength, value){
    value = value.toString();

    if( value.length >= totalLength ){
        return value;
    }else{
        return padLeft(pad, totalLength, pad + value);
    }
}

The example we were using was to ensure that numbers were padded with 0 to the left to make a max length of 6. Here is an example set:

function l(p,t,v){v+="";return v.length>=t?v:l(p,t,p+v);}

var vals = [6451,123,466750];

var pad = l(0,6,vals[0]);// pad with 0's, max length 6

var pads = vals.map(function(i){ return l(0,6,i) });

document.write(pads.join("<br />"));
Fipple answered 4/12, 2015 at 21:8 Comment(0)
Y
1

A little late, but thought I might share anyway. I found it useful to add a prototype extension to Object. That way I can pad numbers and strings, left or right. I have a module with similar utilities I include in my scripts.

// include the module in your script, there is no need to export
var jsAddOns = require('<path to module>/jsAddOns');

~~~~~~~~~~~~ jsAddOns.js ~~~~~~~~~~~~

/* 
 * method prototype for any Object to pad it's toString()
 * representation with additional characters to the specified length
 *
 * @param padToLength required int
 *     entire length of padded string (original + padding)
 * @param padChar optional char
 *     character to use for padding, default is white space
 * @param padLeft optional boolean
 *     if true padding added to left
 *     if omitted or false, padding added to right
 *
 * @return padded string or
 *     original string if length is >= padToLength
 */
Object.prototype.pad = function(padToLength, padChar, padLeft) {    

    // get the string value
    s = this.toString()

    // default padToLength to 0
    // if omitted, original string is returned
    padToLength = padToLength || 0;

    // default padChar to empty space
    padChar = padChar || ' ';


    // ignore padding if string too long
    if (s.length >= padToLength) {
        return s;
    }

    // create the pad of appropriate length
    var pad = Array(padToLength - s.length).join(padChar);

    // add pad to right or left side
    if (padLeft) {
        return pad  + s;        
    } else {
        return s + pad;
    }
};
Yonina answered 13/3, 2016 at 14:51 Comment(0)
I
1
  1. Never insert data somewhere (especially not at beginning, like str = pad + str;), since the data will be reallocated everytime. Append always at end!
  2. Don't pad your string in the loop. Leave it alone and build your pad string first. In the end concatenate it with your main string.
  3. Don't assign padding string each time (like str += pad;). It is much faster to append the padding string to itself and extract first x-chars (the parser can do this efficiently if you extract from first char). This is exponential growth, which means that it wastes some memory temporarily (you should not do this with extremely huge texts).

if (!String.prototype.lpad) {
    String.prototype.lpad = function(pad, len) {
        while (pad.length < len) {
            pad += pad;
        }
        return pad.substr(0, len-this.length) + this;
    }
}

if (!String.prototype.rpad) {
    String.prototype.rpad = function(pad, len) {
        while (pad.length < len) {
            pad += pad;
        }
        return this + pad.substr(0, len-this.length);
    }
}
Intercolumniation answered 19/8, 2016 at 2:53 Comment(0)
P
0

Here's my take:

I'm not so sure about its performance, but I find it much more readable than other options I saw around here...

var replicate = function(len, char) {
  return Array(len + 1).join(char || ' ');
};

var padr = function(text, len, char) {
  if (text.length >= len)
    return text;
  return text + replicate(len-text.length, char);
};
Piranha answered 14/5, 2013 at 2:17 Comment(0)
I
0
  1. function

    var _padLeft = function(paddingString, width, replacementChar) {
        return paddingString.length >= width ? paddingString : _padLeft(replacementChar + paddingString, width, replacementChar || ' ');
    };
    
  2. String prototype

    String.prototype.padLeft = function(width, replacementChar) {
            return this.length >= width ? this.toString() : (replacementChar + this).padLeft(width, replacementChar || ' ');
    };
    
  3. slice

    ('00000' + paddingString).slice(-5)
    
Inextinguishable answered 14/3, 2014 at 13:38 Comment(0)
J
0

Based on the best answers of this question I have made a prototype for String called padLeft (exactly like we have in C#):

String.prototype.padLeft = function (paddingChar, totalWidth) {
    if (this.toString().length >= totalWidth)
        return this.toString();

    var array = new Array(totalWidth); 

    for (i = 0; i < array.length; i++)
        array[i] = paddingChar;

    return (array.join("") + this.toString()).slice(-array.length);
}

Usage:

var str = "12345";
console.log(str.padLeft("0", 10)); //Result is: "0000012345"

JsFiddle

Jacobite answered 7/7, 2014 at 21:27 Comment(0)
A
0
String.prototype.padLeft = function(pad) {
        var s = Array.apply(null, Array(pad)).map(function() { return "0"; }).join('') + this;
        return s.slice(-1 * Math.max(this.length, pad));
    };

usage:

  1. "123".padLeft(2) returns: "123"
  2. "12".padLeft(2) returns: "12"
  3. "1".padLeft(2) returns: "01"
Agonist answered 25/3, 2015 at 10:15 Comment(0)
D
0

All options included

function padding(stringToBePadded, paddingCharacter, totalLength, padLeftElseRight){
    //will pad any string provided in first argument, with padding character provide in 2nd argument and truncate to lenght provided in third argument, padding left if 4th argument true or undefined, right if false. 
    // i.e. padding("lode","x","10")  -->  "xxxxxxlode"
    // i.e. padding("lode","x","10",true)  -->  "xxxxxxlode"
    // i.e. padding("lode","x","10",false)  -->  "lodexxxxxx"
    // i.e. padding("12","0","5")  -->  "00012"
    {
        padLeftElseRight = typeof padLeftElseRight !== 'undefined' ? padLeftElseRight : true;
    }
    if (stringToBePadded.length > totalLength){
        // console.log("string too long to be padded");
        return stringToBePadded;
    }
    var paddingString = paddingCharacter.repeat(totalLength);//make long string of padding characters
    if ( padLeftElseRight){
        return String(paddingString+stringToBePadded).slice(-totalLength);
    }else{ 
        return String(stringToBePadded+paddingString).slice(0,totalLength); 
    }
}
Dewberry answered 12/5, 2015 at 19:44 Comment(0)
M
0

I like to do this in case you ever need to pad with multiple characters or tags (e.g. &nbsp;) for display:

$.padStringLeft = function(s, pad, len) {
    if(typeof s !== 'undefined') {
        var c=s.length; while(len > c) {s=pad+s;c++;}
    }
    return s;
}    

$.padStringRight = function(s, pad, len) {
    if(typeof s !== 'undefined') {
        var c=s.length; while(len > c) {s += pad;c++;}
    }
    return s;
}
Muttonchops answered 18/8, 2015 at 18:20 Comment(0)
D
0

my combination of aboves solutions added to my own, always evolving version :)

//in preperation for ES6
String.prototype.lpad || (String.prototype.lpad = function( length, charOptional )
{
    if (length <= this.length) return this;
    return ( new Array((length||0)+1).join(String(charOptional)||' ') + (this||'') ).slice( -(length||0) );
});


'abc'.lpad(5,'.') == '..abc'
String(5679).lpad(10,0) == '0000005679'
String().lpad(4,'-') == '----' // repeat string
Diakinesis answered 26/8, 2015 at 4:9 Comment(0)
G
0

use repeat, it would be more simple.

    var padLeft=function(str, pad, fw){
        return fw>str.length ? pad.repeat(fw-str.length)+str : str;
    }

you can use it like: padeLeft('origin-str', '0', 20)

Grammalogue answered 26/10, 2016 at 3:29 Comment(0)
E
0

One liner if you want something compact:

String.prototype.pad = function(len, chr){
        return((((new Array(len)).fill(chr)).join("") +this).substring(this.length));
}
Edward answered 4/11, 2016 at 1:21 Comment(0)
F
0

this is my version of function:

function str_pad(str, size, char, right) {
    var s = str + "";
    while (s.length < size) {
        if (right) {
            s = s + char;
        } else {
            s = char + s;
        }
    }
    return s;
}
Feigned answered 31/1, 2017 at 5:43 Comment(0)
L
0

For something like this, I might create a one-line function at the point where it is needed:

var padleft = (s,c,len) => { while(s.length < len) s = c + s; return s; }

Example:

> console.log( padleft( '110', '0', 8) );
> 00000110
Laius answered 14/2, 2017 at 16:11 Comment(0)
G
0

The incredibly simple way to right pad a string,

say max length ten, is

name = (name + "                    ").substring(0,10)
Gribble answered 15/2 at 19:46 Comment(0)
D
-1

Try this:

function leftPad(number) {
    return (number < 9) ? '0' + number : number;
}

// Call it like this
var month = 3;
month = leftPad(month); // Output: month=04
Dercy answered 30/12, 2014 at 5:59 Comment(0)
W
-1

Like PHP:

const STR_PAD_RIGHT = 1;
const STR_PAD_LEFT = 0;
const STR_PAD_BOTH = 2;

/**
 * @see http://php.net/str_pad
 * @param mixed input 
 * @param integer length 
 * @param string string 
 * @param integer type 
 * @return string
 */
function str_pad(input, length, string, type) {
    if (type === undefined || (type !== STR_PAD_LEFT && type !== STR_PAD_BOTH)) {
        type = STR_PAD_RIGHT
    }

    if (input.toString().length >= length) {
         return input;
    } else {
        if (type === STR_PAD_BOTH) {
            input = (string + input + string);
        } else if (type == STR_PAD_LEFT) {
            input = (string + input);
        } else {
            input = (input + string);
        }

        return str_pad(input.toString(), length, string, type);
    }
}
Wallpaper answered 11/8, 2016 at 12:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.