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
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: 909.322
    // 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
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 & 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?

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 = " "), (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

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

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
45
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;
      }

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 "in the works" so that people don't duplicate effort?


Contribute a New function