JavaScript str_pad
Returns input string padded on the left or right to specified length with pad_string
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 3031 32 33 34 3536 37 38 39 40 | function str_pad (input, pad_length, pad_string, pad_type) { // Returns input string padded on the left or right to specified length with pad_string // // version: 1008.1718 // discuss at: http://phpjs.org/functions/str_pad // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + namespaced by: Michael White (http://getsprink.com) // + input by: Marco van Oort // + bugfixed by: Brett Zamir (http://brett-zamir.me) // * example 1: str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT'); // * returns 1: '-=-=-=-=-=-Kevin van Zonneveld' // * example 2: str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH'); // * returns 2: '------Kevin van Zonneveld-----' var half = '', 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; }; input += ''; pad_string = pad_string !== undefined ? pad_string : ' '; if (pad_type != 'STR_PAD_LEFT' && pad_type != 'STR_PAD_RIGHT' && pad_type != 'STR_PAD_BOTH') { pad_type = 'STR_PAD_RIGHT'; } if ((pad_to_go = pad_length - input.length) > 0) { if (pad_type == 'STR_PAD_LEFT') { input = str_pad_repeater(pad_string, pad_to_go) + input; } else if (pad_type == 'STR_PAD_RIGHT') { input = input + str_pad_repeater(pad_string, pad_to_go); } else if (pad_type == 'STR_PAD_BOTH') { half = str_pad_repeater(pad_string, Math.ceil(pad_to_go/2)); input = half + input + half; input = input.substr(0, pad_length); } } return input; } |
Examples
» Example 1
Running
1 | str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT'); |
Should return
1 | '-=-=-=-=-=-Kevin van Zonneveld' |
» Example 2
Running
1 | str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH'); |
Should return
1 | '------Kevin van Zonneveld-----' |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have str_pad goodness in JavaScript.
@Kevin van Zonneveld:
Thanks for your feedback. I will check the second test case tomorrow and test the function with some "edge"-scenarios.
Regarding the lint warning about using len before it being declared, I used this JS feature to get undefined value without using global undefined variable, but now I think I should have used it, cause I'm already using global Array function and some other phpjs function also use these variables. I will rewrite this part too (there are many more possibilities to get undefined value, or I could just declare the variable at the very beginning). We/You should also define some rules about using global variables/functions/constructors like undefined, Array, as their usage isn't always safe, cause they can be overwritten. Some developers avoid using them and some just don't bother at all.
About using conditional operator, I don't see anything wrong with it. I think, in this case the code is well self-explaining.
Hey there Rafal,
My second testcase returned: -----Kevin van Zonneveld------ with your function. So that needs a bit of tinkering still.
Also jslint said:
Lint at line 17 character 13: 'len' was used before it was defined.
var len =
Then on a personal note, I can't say I'm the world's biggest fan of concatenating ? : constructions as they tend to lead to short, but more difficult to maintain code.
However in this case I feel the maintainability is still improved compared to the current implementation so I'd probably still include it in php.js
Thanks so much!
Oh, sorry, I shouldn't also accept empty string. Please change
pad_string = String(pad_string === len ? ' ' : pad_string);
to
pad_string = (pad_string !== len && ''+pad_string) || ' ';
My approach to str_pad
function str_pad(input, pad_length, pad_string, pad_type){
input += ''; // casting any type to string
pad_length |= 0; // casting any type to integer
pad_string = String(pad_string === len ? ' ' : pad_string); // checking for undefined value for pad_string
var charsRequired = Math.max(0, pad_length - input.length);
pad_string = Array(Math.ceil(charsRequired / pad_string.length) + 1).join(pad_string);
var len =
pad_type === 'STR_PAD_BOTH' ?
[charsRequired / 2 | 0, Math.ceil(charsRequired / 2)] :
pad_type === 'STR_PAD_LEFT' ?
[charsRequired, 0] :
[0, charsRequired];
return pad_string.substr(0, len[0]) + input + pad_string.substr(0, len[1]);
}
It's a bit shorter. I think the performance will be slightly worser cause of using Array(len).join().
Regarding the pad_string parameter. I am converting any value except undefined to string. When undefined is passed, a string containing 1 space character is used instead.
I thought it would be worth mentioning the following:
according to php.net, the third parameter should have a default value of an interspace, e.g. $pad_string = " ";.
I do not know what exactly is the best way to set such a default value, but anyway, I would suggest to add this default value so this function is more equilavent to php's function.
@ Jonas Raoni & Philip: I think we should stick with speed & readability. For compactness, people can optionally use a minified version, but it makes development with multiple coders a bit harder to make such a compact version the leading one. Do you guys agree?
Hmm, the one we have is actually somewhat faster, at least in Firefox. It does seem more compact, though.
I didn't saw this pad before, I've made one a long time ago if you find it useful here it is (sorry about the format, I'm lazy to change the codes hehe):
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;
};
l = length
s = string
t = if 0 pads on the left, if 1 right, if 2 both sides
@ waldo malqui silva: No Problem! I've included your name in my function. If you have any remarks on it, let me know!
@ waldo malqui silva : I was just working on count, and trimmed it down a bit:
http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_count/
Does this also seem right to you, or am I overlooking something?
Sorry Kevin, I don't read your function list, anyway if my implementation of PHP's count is good you can use :))))
Hi this is my implementation of PHP's count
[CODE="Javascript"]
var Prueba = [1,2,3,4,5,6,7,8,9,0];
var Prueba2 = null;
var Prueba3 = 'waldo';
var Prueba4 = false;
var Prueba5 = [[[1,['a','b','c'],3],2,3,4,5],['a','b','c','d','e'],[1,2,3,4,5],['a','b','c','d','e'],[1,2,3,4,5]];
var Prueba6 = {
'one' : [1,2,3,4,5],
'two' : ['a','b','c'],
'fun' : function () {
alert ( 'Testing...' );
},
'four' : { 'values' : [1,2,3,4,5,6] }
}
alert ( count ( Prueba6, 'COUNT_RECURSIVE' ) );
function count ( mixed_var, mode) {
var elements = 0;
if ( mixed_var instanceof Array ) {
if ( mode == 'COUNT_RECURSIVE' || mode == 1 ) {
for ( var item in mixed_var ) {
if ( mixed_var[item] instanceof Array || mixed_var[item] instanceof Object ) {
elements += count ( mixed_var[item], 'COUNT_RECURSIVE' );
}
elements++;
}
} else {
elements = mixed_var.length;
}
} else if ( mixed_var instanceof Object ) {
for ( var item in mixed_var ) {
if ( mixed_var[item] instanceof Array || mixed_var[item] instanceof Object ) {
if ( mode == 'COUNT_RECURSIVE' || mode == 1 ) {
elements += count ( mixed_var[item], 'COUNT_RECURSIVE' );
}
elements++;
}
}
} else if ( mixed_var != null ) {
elements = 1;
}
return elements;
}
[/CODE]


Rafał Kukawski
Apr 29th