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:
Code:
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.
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"
Here's my take
I'm not so sure about it's 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);
};
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).
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
default pad is 2 chars
default char is 0
so i can simply write
padL(1);
// 01
if i add the second argument (pad width)
padL(1,3);
// 001
third parameter (pad char)
padL('zzz',10,'x');
// xxxxxxxzzz
EDIT
@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)
}
works also 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 ... thats not my problem.
Said that i 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 wanna 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 max 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"
*/
With ES8, there are two options for padding.
You can check them in the documentation.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart