Use PHP functions in JavaScript

JavaScript vprintf

Output a formatted 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
30
function vprintf (format, args) {
    // Output a formatted string  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/vprintf    // +   original by: Ash Searle (http://hexmen.com/blog/)
    // +   improved by: Michael White (http://getsprink.com)
    // + reimplemented by: Brett Zamir (http://brett-zamir.me)
    // -    depends on: sprintf
    // *     example 1: printf("%01.2f", 123.1);    // *     returns 1: 6
    var body, elmt;
    var ret = '',
        d = this.window.document;
     // .shift() does not work to get first item in bodies
    var HTMLNS = 'http://www.w3.org/1999/xhtml';
    body = d.getElementsByTagNameNS ? (d.getElementsByTagNameNS(HTMLNS, 'body')[0] ? d.getElementsByTagNameNS(HTMLNS, 'body')[0] : d.documentElement.lastChild) : d.getElementsByTagName('body')[0];
 
    if (!body) {        return false;
    }
 
    ret = this.sprintf.apply(this, [format].concat(args));
     elmt = d.createTextNode(ret);
    body.appendChild(elmt);
 
    return ret.length;
}
external links: original PHP docs | raw js source

Examples

Running

1
printf("%01.2f", 123.1);

Should return

1
6

Dependencies

In order to use this function, you also need:

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 vprintf 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

No comments yet. Be the first!


Contribute a New function