phpjs
Version:
74 lines (58 loc) • 2.27 kB
Markdown
layout: page
title: "JavaScript vprintf function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/vprintf:579
- /functions/view/vprintf
- /functions/view/579
- /functions/vprintf:579
- /functions/579
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's vprintf
{% codeblock strings/vprintf.js lang:js https://raw.github.com/kvz/phpjs/master/functions/strings/vprintf.js raw on github %}
function vprintf (format, args) {
// From: http://phpjs.org/functions
// + 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: vprintf("%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;
}
{% endcodeblock %}
- [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/strings/vprintf.js)
Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are
the closest match to this hashtable-like data structure.
Please also note that php.js offers community built functions and goes by the
[McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online
functions that are far from perfect, in the hopes to spark better contributions.
Do you have one? Then please just:
- [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/strings/vprintf.js)
### Example 1
This code
{% codeblock lang:js example %}
vprintf("%01.2f", 123.1);
{% endcodeblock %}
Should return
{% codeblock lang:js returns %}
6
{% endcodeblock %}
### Other PHP functions in the strings extension
{% render_partial _includes/custom/strings.html %}