Use PHP functions in JavaScript

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
4041
42
43
44
4546
47
48
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: 1109.2015
    // 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;
}
external links: original PHP docs | raw js source

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.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
Chris Wright
8 Mar '11 Permalink

q  - Added support for integer values of STR_PAD_x constants as defined in PHP.
- Removed unused variable 'i' from private member 'str_pad_repeater'

function str_pad (input, pad_length, pad_string, pad_type) {
    // http://kevin.vanzonneveld.net
    // +   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 = '';

        while (collect.length < len) {
            collect += s;
        }
        collect = collect.substr(0, len);

        return collect;
    };

    input += '';
    pad_string = pad_string !== undefined ? pad_string : ' ';

    switch (pad_type) {
        case 'STR_PAD_LEFT':
        case 0:
            pad_type = 0;
              break;
        case 'STR_PAD_BOTH':
        case 2:
            pad_type = 2;
            break;
        case 'STR_PAD_RIGHT':
        case 1:
        default:
            pad_type = 1;
            break;
    }

    if ((pad_to_go = pad_length - input.length) > 0) {
        if (pad_type == 0) { // Pad left
            input = str_pad_repeater(pad_string, pad_to_go) + input;
        } else if (pad_type == 1) { // Pad right
            input = input + str_pad_repeater(pad_string, pad_to_go);
        } else if (pad_type == 2) { // 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;
}

Gravatar
Rafał Kukawski
29 Apr '10 Permalink

q  Regarding the second test case, str_pad on my server (php version 5.2.12) when using STR_PAD_BOTH, first padds from right and then from left, so when there are for example 15 characters to be added, 8 characters are added to the right and 7 to the left. If it's not the case on your server or on a newer PHP version, please inform and we'll align our code.

Gravatar
Rafał Kukawski
29 Apr '10 Permalink

q  @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.

Gravatar
Kevin van Zonneveld
29 Apr '10 Permalink

q  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!

Gravatar
Rafał Kukawski
28 Apr '10 Permalink

q  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) || ' ';

Gravatar
Rafał Kukawski
28 Apr '10 Permalink

q  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.

Gravatar
Brett Zamir
22 Aug '09 Permalink

q  Good catch--fixed.

Gravatar
Marco van Oort
21 Aug '09 Permalink

q  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.

Gravatar
Kevin van Zonneveld
17 Apr '08 Permalink

q  @ Jonas Raoni &amp; Philip: I think we should stick with speed &amp; 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?

Gravatar
Philip
17 Apr '08 Permalink

q  Hmm, the one we have is actually somewhat faster, at least in Firefox. It does seem more compact, though.

Gravatar
Jonas Raoni
17 Apr '08 Permalink

q  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 = &quot; &quot;), (l -= this.length) &gt; 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

Gravatar
Kevin van Zonneveld
9 Jan '08 Permalink

q  @ waldo malqui silva: No Problem! I've included your name in my function. If you have any remarks on it, let me know!

Gravatar
Kevin van Zonneveld
9 Jan '08 Permalink

q  @ 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?

Gravatar
waldo malqui silva
9 Jan '08 Permalink

q  Sorry Kevin, I don't read your function list, anyway if my implementation of PHP's count is good you can use :))))

Gravatar
waldo malqui silva
9 Jan '08 Permalink

q  Hi this is my implementation of PHP's count

[CODE=&quot;Javascript&quot;]
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]

Gravatar
Kevin van Zonneveld
5 Jan '08 Permalink

q  @ Aaron Saray: Thanks for the suggestion, I've added a section: 'In The Works', which will be updated on every page.

Gravatar
Aaron Saray
5 Jan '08 Permalink

q  Do you have a list of functions that are &quot;in the works&quot; so that people don't duplicate effort?


Contribute a New function