Mnah... I have not seen a "ultimate" answer to this issue and if you are facing the same challenge I must save you some time by saying that saddly there's not built-in function for that on JavaScript; but there's this awesome function in PHP that does a great job on padding strings as well as numbers with single character or arbitrary strings so after some time of banging my head for not having the right tool on JS [mostly for zerofillin' numbers and usually for trimming strings to fit a fixed length] and excessive coding work I decided to write my own function that does the same ["almost the same", read on for detail] that the dream PHP function but in comfortable client-side JavaScript.
function str_pad(input,pad_length,pad_string,pad_type){
var input=input.toString();
var output="";
if((input.length>pad_length)&&(pad_type=='STR_PAD_RIGHT')){var output=input.slice(0,pad_length);}
else if((input.length>pad_length)&&(pad_type=='STR_PAD_LEFT')){var output=input.slice(input.length-pad_length,input.length);}
else if((input.length<pad_length)&&(pad_type=='STR_PAD_RIGHT')){
var caracteresNecesarios=pad_length-input.length;
var rellenoEnteros=Math.floor(caracteresNecesarios/pad_string.length);
var rellenoParte=caracteresNecesarios%pad_string.length;
var output=input;
for(var i=0;i<rellenoEnteros;i++){var output=output+pad_string;};
var output=output+pad_string.slice(0,rellenoParte);
}
else if((input.length<pad_length)&&(pad_type=='STR_PAD_LEFT')){
var caracteresNecesarios=pad_length-input.length;
var rellenoEnteros=Math.floor(caracteresNecesarios/pad_string.length);
var rellenoParte=caracteresNecesarios%pad_string.length;
var output="";
for(var i=0;i<rellenoEnteros;i++){var output=output+pad_string;};
var output=output+pad_string.slice(0,rellenoParte);
var output=output+input;
}
else if(input.length==pad_length){var output=input;};
return output;
};
The only thing that my function does not do is the STR_PAD_BOTH
behavior that I could add with some time and a more comfortable keyboard.
You might call the function and test it; bet you'll love it if you don't mind that inner code uses one or two words in Spanish... not big deal I think. I did not added comments for "watermarking" my coding so you can seamless use it in your work nor I compressed the code for enhanced readability.
Use it and test it like this and spread the code:
alert("str_pad('murcielago',20,'123','STR_PAD_RIGHT')="+str_pad('murcielago',20,'123','STR_PAD_RIGHT')+'.');