» Javascript equivalent for PHP's printf

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: printf.

PHP printf

Description

printf - Output a formatted string

int printf( string format [, mixed args [, mixed ...]] )

formatSee sprintf() for a description of format.

Parameters

  • format

    See sprintf() for a description of format .

  • args

Return Values

Returns the length of the outputted string.

See Also

Javascript printf

Source

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

function printf( ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Ash Searle (http://hexmen.com/blog/)
    // +   improved by: Michael White (http://crestidg.com)
    // -    depends on: sprintf
    // *     example 1: printf("%01.2f", 123.1);
    // *     returns 1: 6
 
    var ret = sprintf.apply(this, arguments);
    document.write(ret);
    return ret.length;
}

To run the Javascript printf, you will also need the following dependencies:

Examples

Currently there is 1 example

Example 1

This is how you could call printf()
printf("%01.2f", 123.1);
And that would return
6

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.

This way code is always checked on syntax errors, and if it doesn't function correctly anymore after an update, we should also be able to detect it more easily.

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:
 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
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
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
spacemedalAlexander Ermolaev (link) for contributing to:
 trim
spacemedalAllan Jensen (link) for contributing to:
 number_format
spacemedalAndrea Giammarchi (link) for contributing to:
 array_map
spacemedalBayron Guevara for contributing to:
 base64_encode
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
spacemedalLeslie Hoare for contributing to:
 rand
spacemedalLincoln Ramsay for contributing to:
 basename
spacemedalMeEtc (link) for contributing to:
 date
spacemedalMick@el for contributing to:
 stripslashes
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
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
spacemedalbaris ozdil for contributing to:
 mktime
spacemedalbooeyOH for contributing to:
 preg_quote
spacemedaldjmix for contributing to:
 basename
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
spacemedaljohn (link) for contributing to:
 html_entity_decode
spacemedalkenneth for contributing to:
 explode
spacemedalpenutbutterjelly for contributing to:
 str_ireplace
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.

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,476 times

Add comment

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

#12. Kevin on 04 March 2008

Kevin@ Michael White: two of them were related to flawed examples of my own ;) but i think there is still some discrepancies between include & require ?

#11. Kevin on 04 March 2008

Kevin@ Michael White: LOL :) No problem dude. Thanks for all of the hard work. There still are some errors though: http://kevin.vanzonneveld.net/pj_tester.php

#10. Michael White on 04 March 2008

Michael WhiteOk, I swear this is my last post tonight. I've just been really busy working on a few things that happen to really coincide with what is being done here with php.js

// This post doesn't have code - just a URL.
// Use the URL in this post to find a source file with a few new functions and some updates to existing functions. It also contains updates to a couple of my own new functions that I have already posted and then found some little discrepancies in.
 
// http://www.sprinkit.net/aether/php_js-updates.js
 
Maybe in the future I will just save all my work on php.js stuff into a single file and post it all at once so this doesn't happen again.

#9. Michael White on 04 March 2008

Michael Whitefloatval() : A nearly pointless addition. Only slightly more than a wrapper for JavaScript's parseFloat() method.

function floatval(mixed_var) {
  // *     example 1: floatval('150.03_page-section');
  // *     return 1: 150.03
  // *     example 2: floatval('page: 3');
  // *     return 2: 0
  // *     example 2: floatval('-50 + 8');
  // *     return 2: -50
  
  // Note: The native parseFloat() method of JavaScript returns NaN when it encounters a string before an int or float value.
  
  return (parseFloat(mixed_var) || 0);
}
http://crestidg.com

#8. Michael White on 04 March 2008

Michael WhiteI ended up nearly rewriting this function...

function printf( ) {
    // *     example 1: printf("%01.2f", 123.1);
    // *     returns 1: 6
 
  var ret = this.sprintf.apply(this, arguments);
  document.write(ret);
  return ret.length;
}
The previous code turned the arguments array into a string representation of that array. With eval() that works properly but with apply() it expects the arguments to be an array. All we have to do is leave the arguments array alone and pass it directly to the apply() function call. The "this" keyword makes sure the proper scope is used and applied to the function whether the code is namespaced or just in the global namespace as a simple function. Why it worked in a namespace when passing string arguments I cannot pretend to know.... but at least it works everywhere now.

#7. Michael White on 04 March 2008

Michael WhiteHmm - not sure I can grab that OS but I'll see if I can get the error on another OS. The good news is that I have a new function: print_r()

function print_r(array, return_val) {
  var output = "", pad_char = " ", pad_val = 3;
  
  function formatArray(obj, cur_depth, pad_val, pad_char) {
    if(cur_depth > 0)
      cur_depth++;
    
    var base_pad = repeat_char(pad_val*cur_depth, pad_char);
    var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
    var str = "";
    
    if(obj instanceof Array) {
      str += "Array\n" + base_pad + "(\n";
      for(var key in obj) {
        if(obj[key] instanceof Array) {
          str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char);
        } else {
          str += thick_pad + "["+key+"] => " + obj[key] + "\n";
        }
      }
      str += base_pad + ")\n";
    } else {
      str = obj.toString(); // They didn't pass in an array.... why? -- Do the best we can to output this object.
    };
    
    return str;
  };
  
  function repeat_char(len, char) {
    var str = "";
    for(var i=0; i < len; i++) { str += char; };
    return str;
  };
  
  output = formatArray(array, 0, pad_val, pad_char);
  
  if(return_val !== true) {
    document.write("<pre>" + output + "</pre>");
  } else {
    return output;
  }
}
 
The <pre> tags here are optional for the version you release (although they are recommended) I like them because unless you have Firefox you probably can't view "generated source" and you won't be able to make sense of the data unless it is formatted.
 
http://crestidg.com -- by the way - how do I add line breaks in this message box?

#6. Kevin on 02 March 2008

Kevin@ Michael White: Firefox 2 with firebug addon on ubunty gutsy

#5. Michael White on 02 March 2008

Michael WhiteWhat browser(s)? I think I have a solution anyway and I'm going to test it as soon as I can obtain that error message.

#4. Kevin on 02 March 2008

KevinMichael White: I agree that that would be better but it currently generates a: 'format has no properties' error on the line with:

return format.replace(regex, function(substring, valueIndex, flags, minWidth, _, precision, type) {

#3. Michael White on 02 March 2008

Michael WhiteThis function can be made a bit more flexible by not using the eval() function. This really helps more when using namespaces to encapsulate the code. Line three in the example shows the line I used when inside a closed namespace.

//ret = eval('sprintf(' + args + ')'); // Old
ret = sprintf.apply(this, args); // New
//ret = this.sprintf.apply(this, args); // When inside a closed namespace.
http://crestidg.com

#2. Kevin on 17 January 2008

Kevin@ someone: Wow I really thought I did my research but similar projects keep popping up. Thank you.

#1. someone on 17 January 2008

someoneThe php.js is a great project. But I know the similar project, p2js.

http://p2js.googlecode.com/svn/trunk/src/