function strPad input fullLen fillStr fillType var str pad_to_go var s

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function strPad (input,fullLen,fillStr,fillType) {
var str = '', pad_to_go;
var str_pad_repeater = function(s, len){
var collect = '', i;
while(collect.length < len) collect += s;
collect = collect.substr(0,len);
return collect;
};
if (fillType != 'FILL_LEFT' && fillType != 'FILL_RIGHT' && fillType != 'FILL_BOTH') {
fillType = 'FILL_RIGHT';
}
if ((pad_to_go = fullLen - input.length) > 0) {
if (fillType == 'FILL_LEFT') {
input = str_pad_repeater(fillStr, pad_to_go) + input;
} else if (fillType == 'FILL_RIGHT') {
input = input + str_pad_repeater(fillStr, pad_to_go);
} else if (fillType == 'FILL_BOTH') {
str = str_pad_repeater(fillStr, Math.ceil(pad_to_go/2));
input = str + input + str;
input = input.substr(0, fullLen);
}
}
return input;
}
console.log(strPad('star', 10, '-*-'));
console.log(strPad('star', 8, '-*-', 'FILL_LEFT'));
console.log(strPad('star', 8, '*', 'FILL_BOTH'));