Pads a string left or right to a certain length. If the length of the string is bigger than the value of n, the string is truncated.
str is the value to pad; n is the total length. Positive for right padding and negative for left padding. ch is optional and denotes the pad character. It defaults to a space, when str is a string. When str is a number, ch defaults to a zero.function pad(str,n,ch) { if(typeof str=='number') { str=String(str); if(arguments.length<3) ch='0'; } var N=Math.abs(n); if(str.length>=N) { return n>=0 ? str.substr(0, n) : str.substr(str.length-N); } return (n>=0 ? str : '') + new Array(N-str.length+1).join((ch||' ').charAt(0)) + (n<0 ? str : ''); }
Some examples used as unit-test, inspired by Python's doctest.
function tst(a,b) { if(arguments.length==1) console.log("Starting: "+a); else console[a==b ? "info" : "error"]("[%s|%s]", a, b); } tst("PAD test"); tst("doe", pad('doeke', 3)); tst("doeke", pad('doeke', 5)); tst("doeke ", pad('doeke', 7)); tst("eke", pad('doeke', -3)); tst("doeke", pad('doeke', -5)); tst(" doeke", pad('doeke', -7)); tst("0123", pad("123", -4, "0")); tst("0123", pad(123, -4));