» Javascript equivalent for PHP's str_pad

PHP to Javascript Project: php.js

php.jsThis article is part of the 'Porting PHP to Javascript' Project, which aims to decrease the gap between developing for PHP & Javascript.

A lot of people are familiar with PHP's functions, and though Javascript functions are often quite similar, some functions may be missing or addressed differently. The Javascript implementations should be as compliant with the PHP versions as possible, a good indication is that the PHP function manual could also apply to the Javascript version.

Porting crucial PHP functions to Javascript can be fun & useful. Currently some PHP functions have been added, but readers are encouraged to contribute and improve functions by adding comments. Eventually the goal is to save all the functions in one php.js file and make it publicly available for your coding pleasure.

If you choose to contribute, let me know how you want to be credited in the function's comments. You may also want to subscribe to RSS so you receive updates whenever new functions are posted.

This is a Javascript version of the PHP function: str_pad.

PHP str_pad

Description

str_pad - Pad a string to a certain length with another string

string str_pad( string input , int pad_length [, string pad_string [, int pad_type]] )

This functions returns the input string padded on the left, the right, or both sides to the specified padding length. If the optional argument pad_string is not supplied, the input is padded with spaces, otherwise it is padded with characters from pad_string up to the limit.

Parameters

  • input

    The input string.

  • pad_length

    If the value of pad_length is negative or less than the length of the input string, no padding takes place.

  • pad_string

    Note: The pad_string may be truncated if the required number of padding characters can't be evenly divided by the pad_string 's length.

  • pad_type

    Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT.

Return Values

Returns the padded string.

Javascript str_pad

Source

This is the main source of the Javascript version of PHP's str_pad

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://crestidg.com)
    // *     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;
        };
 
    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

Currently there are 2 examples

Example 1

This is how you could call str_pad()
str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT');
And that would return
'-=-=-=-=-=-Kevin van Zonneveld'

Example 2

This is how you could call str_pad()
str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH');
And that would return
'------Kevin van Zonneveld-----'

More about this Project

Download php.js

To easily include it in your code, every function currently available is stored in

Normal

Namespaced What is 'namespaced?'

To download use Right click, Save Link As
Generally the best way is to use a minified version and gzip it



Testing the functions

The number of functions is growing fast and so it becomes hard to maintain quality.

To defeat that danger of bad code, syntax errors, etc, I've added a new feature: php.js tester.

It is an automatically generated page that includes ALL functions in your browser, and then extracts specific testing information from each function's comments. This info is then used to run the function, and the return value is compared to a predefined one.

If you want, go check it out.


Credits

Respect & awards go to everybody who has contributed in some way so far:

medalmedalMichael White (link) for contributing to:
 array_count_values, get_included_files, include, include_once, require, require_once, md5, number_format, parse_str, printf, sha1, sprintf, str_pad, strnatcmp, http_build_query, floatval, is_object, print_r
spacemedal_argos for contributing to:
 array_fill, array_pad, array_product, array_rand, compact, count, range, abs, defined, ip2long, long2ip, implode, strcmp, ucwords
spacemedalJonas Raoni Soares Silva (link) for contributing to:
 shuffle, abs, setcookie, number_format, number_format, soundex, str_repeat, str_replace, str_rot13, ucwords, wordwrap, wordwrap
spacemedalLegaev Andrey for contributing to:
 end, reset, file, file_get_contents, function_exists, include, include_once, http_build_query, is_array, is_object
spacemedalAtes Goral (link) for contributing to:
 array_change_key_case, array_count_values, array_diff_key, get_class, preg_quote, addslashes, count_chars, str_rot13, stripslashes
spacemedalPhilip Peterson for contributing to:
 sizeof, round, echo, nl2br, str_replace, strchr, urldecode, urlencode, var_export
spacemedalMartijn Wieringa for contributing to:
 array_shift, array_unshift, str_ireplace, str_split, strcasecmp, stripos, strnatcmp, substr
spacemedalWebtoolkit.info (link) for contributing to:
 crc32, md5, sha1, utf8_decode, utf8_encode
 
spacemedalCarlos R. L. Rodrigues (link) for contributing to:
 array_chunk, array_unique, date, levenshtein
spacemedalAsh Searle (link) for contributing to:
 basename, printf, sprintf
spacemedalErkekjetter for contributing to:
 ltrim, rtrim, trim
spacemedalGeekFG (link) for contributing to:
 krsort, ksort, time
spacemedalJohnny Mast (link) for contributing to:
 array_walk, array_walk_recursive, create_function
spacemedald3x for contributing to:
 array, explode, unserialize
spacemedalmarrtins for contributing to:
 array_change_key_case, addslashes, stripslashes
spacemedalAlfonso Jimenez (link) for contributing to:
 array_reduce, strpbrk
spacemedalAman Gupta for contributing to:
 base64_decode, utf8_decode
spacemedalArpad Ray (mailto:arpad@php.net) for contributing to:
 serialize, unserialize
spacemedalKarol Kowalski for contributing to:
 array_reverse, abs
spacemedalMirek Slugen for contributing to:
 htmlspecialchars, htmlspecialchars_decode
spacemedalOnno Marsman for contributing to:
 addslashes, isset
spacemedalThunder.m for contributing to:
 base64_decode, base64_encode
spacemedalTyler Akins (link) for contributing to:
 base64_decode, base64_encode
spacemedalmdsjack (link) for contributing to:
 include, trim
spacemedalAlex for contributing to:
 is_int
spacemedalAlexander Ermolaev (link) for contributing to:
 trim
spacemedalAllan Jensen (link) for contributing to:
 number_format
spacemedalAndrea Giammarchi (link) for contributing to:
 array_map
spacemedalArno for contributing to:
 htmlspecialchars
spacemedalBayron Guevara for contributing to:
 base64_encode
spacemedalBen Bryan for contributing to:
 print_r
spacemedalBenjamin Lupton for contributing to:
 number_format
spacemedalBrad Touesnard for contributing to:
 date
spacemedalBrett Zamir for contributing to:
 str_split
spacemedalCagri Ekin for contributing to:
 parse_str
spacemedalCord for contributing to:
 is_array
spacemedalDavid for contributing to:
 is_numeric
spacemedalDavid James for contributing to:
 get_class
spacemedalDxGx for contributing to:
 trim
spacemedalFGFEmperor for contributing to:
 mktime
spacemedalFelix Geisendoerfer (link) for contributing to:
 array_key_exists
spacemedalFremyCompany for contributing to:
 isset
spacemedalGabriel Paderni for contributing to:
 str_replace
spacemedalHoward Yeend for contributing to:
 number_format
spacemedalJ A R for contributing to:
 end
spacemedalJack for contributing to:
 trim
spacemedalLeslie Hoare for contributing to:
 rand
spacemedalLincoln Ramsay for contributing to:
 basename
spacemedalLuke Godfrey for contributing to:
 strip_tags
spacemedalMeEtc (link) for contributing to:
 date
spacemedalMick@el for contributing to:
 stripslashes
spacemedalNate for contributing to:
 addslashes
spacemedalNathan for contributing to:
 htmlspecialchars
spacemedalNick Callen for contributing to:
 wordwrap
spacemedalOzh for contributing to:
 dirname
spacemedalPedro Tainha (link) for contributing to:
 unserialize
spacemedalPeter-Paul Koch (link) for contributing to:
 date
spacemedalPhilippe Baumann for contributing to:
 empty
spacemedalPyerre for contributing to:
 checkdate
spacemedalSakimori for contributing to:
 strlen
spacemedalSanjoy Roy for contributing to:
 array_diff
spacemedalSimon Willison (link) for contributing to:
 str_replace
spacemedalSteve Clay for contributing to:
 function_exists
spacemedalSteve Hilder for contributing to:
 strcmp
spacemedalSteven Levithan (link) for contributing to:
 trim
spacemedalT0bsn for contributing to:
 crc32
spacemedalThiago Mata (link) for contributing to:
 call_user_func_array
spacemedalTim Wiel for contributing to:
 date
spacemedalXoraX (link) for contributing to:
 dirname
spacemedalYannoo for contributing to:
 mktime
spacemedalbaris ozdil for contributing to:
 mktime
spacemedalbooeyOH for contributing to:
 preg_quote
spacemedaldjmix for contributing to:
 basename
spacemedaldptr1988 for contributing to:
 unserialize
spacemedalduncan for contributing to:
 array_unique
spacemedalecho is bad for contributing to:
 echo
spacemedalgabriel paderni for contributing to:
 mktime
spacemedalger for contributing to:
 html_entity_decode
spacemedalgorthaur for contributing to:
 strcmp
spacemedaljakes for contributing to:
 mktime
spacemedaljohn (link) for contributing to:
 html_entity_decode
spacemedaljohnrembo for contributing to:
 var_export
spacemedalkenneth for contributing to:
 explode
spacemedalloonquawl for contributing to:
 htmlspecialchars_decode
spacemedalmetjay for contributing to:
 time
spacemedalpenutbutterjelly for contributing to:
 str_ireplace
spacemedalsankai for contributing to:
 array_count_values
spacemedalsowberry for contributing to:
 utf8_encode
spacemedalstensi for contributing to:
 intval

Your name here?

Contributing is as easy as adding a comment with better code, or code for a new function.
Any contribution leading to improvement will directly get your name & link here.


Coming Project features

Project features that we are currently working on:

  • Versioning. Individual functions are versioned, but the entire library should be versioned as well.
  • Light. A lightweight version of php.js should be made available with only common functions in it.
  • Site. A place for PHP.JS of it's own. You can track our lame attempts at phpjs.org (not hyperlinked deliberately). If there are any CakePHP developers out there who would like to contribute, contact me.
  • Testsuite. A better test-suite that can be ran locally so developers can easily test before commiting. Also the testing itself should be more thorough.

Like this article?

   Then Dzone it!
Or use another bookmark button below to show your support &
help me spread the word.


tags: programming, php, javascript
category: Programming - Javascript - PHP equivalents
read: 1,983 times

Add comment

(required, shown)(required, not shown)for syntax highlighting

[CODE="Javascript"]
your_code_here();
[/CODE]

Replace "Javascript"
with "php", "text", etc.
code (to make sure you are not a spammer)

Comments

#9. Kevin on 17 April 2008

Member avatar: Kevin@ 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?

#8. Philip on 17 April 2008

Default avatar:PhilipHmm, the one we have is actually somewhat faster, at least in Firefox. It does seem more compact, though.

#7. Jonas Raoni on 17 April 2008

Default avatar:Jonas RaoniI 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))
... [more] + 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

#6. Kevin on 09 January 2008

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

#5. Kevin on 09 January 2008

Member avatar: Kevin@ 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?

#4. waldo malqui silva on 09 January 2008

Default avatar:waldo malqui silvaSorry Kevin, I don't read your function list, anyway if my implementation of PHP's count is good you can use :))))

#3. waldo malqui silva on 09 January 2008

Default avatar:waldo malqui silvaHi this is my implementation of PHP's count

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

#2. Kevin on 05 January 2008

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

#1. Aaron Saray on 05 January 2008

Default avatar:Aaron SarayDo you have a list of functions that are "in the works" so that people don't duplicate effort?