» Javascript equivalent for PHP's sprintf
226 PHP equivalents
- PHP.JS Licensing
- PHP.JS SVN
- PHP.JS Namespaced
- abs
- acosh
- acos
- addslashes
- array
- array_change_key_case
- array_chunk
- array_combine
- array_count_values
- array_diff
- array_diff_assoc
- array_diff_key
- array_fill
- array_fill_keys
- array_filter
- array_flip
- array_keys
- array_key_exists
- array_map
- array_merge
- array_merge_recursive
- array_pad
- array_pop
- array_product
- array_push
- array_rand
- array_reduce
- array_reverse
- array_search
- array_shift
- array_slice
- array_splice
- array_sum
- array_unique
- array_unshift
- array_values
- array_walk
- array_walk_recursive
- asinh
- asin
- atanh
- atan
- base64_decode
- base64_encode
- basename
- base_convert
- bin2hex
- bindec
- call_user_func
- call_user_func_array
- ceil
- checkdate
- chop
- chr
- chunk_split
- class_exists
- compact
- constant
- cosh
- cos
- count
- count_chars
- crc32
- create_function
- date
- decbin
- dechex
- decoct
- defined
- define
- deg2rad
- die
- dirname
- each
- echo
- empty
- end
- exit
- explode
- exp
- filesize
- file
- file_exists
- file_get_contents
- floatval
- floor
- fmod
- function_exists
- func_get_args
- func_get_arg
- func_num_args
- getdate
- getrandmax
- gettype
- get_class
- get_defined_functions
- get_defined_vars
- get_headers
- get_html_translation_table
- get_included_files
- hexdec
- htmlentities
- htmlspecialchars
- htmlspecialchars_decode
- html_entity_decode
- http_build_query
- hypot
- implode
- include
- include_once
- intval
- in_array
- ip2long
- isset
- is_array
- is_bool
- is_double
- is_finite
- is_float
- is_infinite
- is_integer
- is_int
- is_long
- is_nan
- is_null
- is_numeric
- is_object
- is_scalar
- is_string
- join
- krsort
- ksort
- lcg_value
- levenshtein
- log10
- log
- long2ip
- ltrim
- max
- md5
- md5_file
- method_exists
- microtime
- min
- mktime
- mt_getrandmax
- mt_rand
- nl2br
- number_format
- octdec
- ord
- parse_str
- pi
- pow
- preg_quote
- printf
- print_r
- property_exists
- quotemeta
- rad2deg
- rand
- range
- require
- require_once
- reset
- round
- rsort
- rtrim
- serialize
- setcookie
- sha1
- sha1_file
- shuffle
- sinh
- sin
- sizeof
- sleep
- sort
- soundex
- split
- » sprintf
- sqrt
- strcasecmp
- strchr
- strcmp
- stripos
- stripslashes
- strip_tags
- stristr
- strlen
- strnatcmp
- strncasecmp
- strpbrk
- strpos
- strrev
- strripos
- strrpos
- strspn
- strstr
- strtolower
- strtotime
- strtoupper
- str_ireplace
- str_pad
- str_repeat
- str_replace
- str_rot13
- str_split
- substr
- substr_count
- tanh
- tan
- time
- trim
- ucfirst
- ucwords
- unserialize
- urldecode
- urlencode
- utf8_decode
- utf8_encode
- var_export
- wordwrap
PHP to Javascript Project: php.js
This 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: sprintf.
PHP sprintf
Description
sprintf - Return a formatted string
string sprintf( string format [, mixed args [, mixed ...]] )
Returns a string produced according to the formatting string format.
Parameters
-
format
The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result, and conversion specifications, each of which results in fetching its own parameter. This applies to both sprintf() and printf().
Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:
- An optional sign specifier that forces a sign (- or +) to be used on a number. By default, only the - sign is used on a number if it's negative. This specifier forces positive numbers to have the + sign attached as well, and was added in PHP 4.3.0.
- An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ('). See the examples below.
- An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a - character here will make it left-justified.
- An optional number, a width specifier that says how many characters (minimum) this conversion should result in.
- An optional precision specifier that says how many decimal digits should be displayed for floating-point numbers. When using this specifier on a string, it acts as a cutoff point, setting a maximum character limit to the string.
-
A type specifier that says what type the argument data should be treated as. Possible types:
- % - a literal percent character. No argument is required.
- b - the argument is treated as an integer, and presented as a binary number.
- c - the argument is treated as an integer, and presented as the character with that ASCII value.
- d - the argument is treated as an integer, and presented as a (signed) decimal number.
- e - the argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).
- u - the argument is treated as an integer, and presented as an unsigned decimal number.
- f - the argument is treated as a float, and presented as a floating-point number (locale aware).
- F - the argument is treated as a float, and presented as a floating-point number (non-locale aware). Available since PHP 4.3.10 and PHP 5.0.3.
- o - the argument is treated as an integer, and presented as an octal number.
- s - the argument is treated as and presented as a string.
- x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
- X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).
-
The format string supports argument numbering/swapping. Here is an example:
Example#1 Argument swapping
<?phpThis might output, "There are 5 monkeys in the tree". But imagine we are creating a format string in a separate file, commonly because we would like to internationalize it and we rewrite it as:
$format = 'There are %d monkeys in the %s';
printf($format, $num, $location);
?>Example#2 Argument swapping
<?phpWe now have a problem. The order of the placeholders in the format string does not match the order of the arguments in the code. We would like to leave the code as is and simply indicate in the format string which arguments the placeholders refer to. We would write the format string like this instead:
$format = 'The %s contains %d monkeys';
printf($format, $num, $location);
?>Example#3 Argument swapping
<?phpAn added benefit here is that you can repeat the placeholders without adding more arguments in the code. For example:
$format = 'The %2$s contains %1$d monkeys';
printf($format, $num, $location);
?>Example#4 Argument swapping
<?php
$format = 'The %2$s contains %1$d monkeys.
That\'s a nice %2$s full of %1$d monkeys.';
printf($format, $num, $location);
?> - args
Return Values
Returns a string produced according to the formatting string format .
See Also
Javascript sprintf
Source
This is the main source of the Javascript version of PHP's sprintf
function sprintf( ) { // http://kevin.vanzonneveld.net // + original by: Ash Searle (http://hexmen.com/blog/) // + namespaced by: Michael White (http://getsprink.com) // + tweaked by: Jack // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: Paulo Ricardo F. Santos // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // * example 1: sprintf("%01.2f", 123.1); // * returns 1: 123.10 // * example 2: sprintf("[%10s]", 'monkey'); // * returns 2: '[ monkey]' // * example 3: sprintf("[%'#10s]", 'monkey'); // * returns 3: '[####monkey]' var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g; var a = arguments, i = 0, format = a[i++]; // pad() var pad = function(str, len, chr, leftJustify) { if (!chr) chr = ' '; var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr); return leftJustify ? str + padding : padding + str; }; // justify() var justify = function(value, prefix, leftJustify, minWidth, zeroPad, customPadChar) { var diff = minWidth - value.length; if (diff > 0) { if (leftJustify || !zeroPad) { value = pad(value, minWidth, customPadChar, leftJustify); } else { value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length); } } return value; }; // formatBaseX() var formatBaseX = function(value, base, prefix, leftJustify, minWidth, precision, zeroPad) { // Note: casts negative numbers to positive ones var number = value >>> 0; prefix = prefix && number && {'2': '0b', '8': '0', '16': '0x'}[base] || ''; value = prefix + pad(number.toString(base), precision || 0, '0', false); return justify(value, prefix, leftJustify, minWidth, zeroPad); }; // formatString() var formatString = function(value, leftJustify, minWidth, precision, zeroPad, customPadChar) { if (precision != null) { value = value.slice(0, precision); } return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar); }; // finalFormat() var doFormat = function(substring, valueIndex, flags, minWidth, _, precision, type) { if (substring == '%%') return '%'; // parse flags var leftJustify = false, positivePrefix = '', zeroPad = false, prefixBaseX = false, customPadChar = ' '; var flagsl = flags.length; for (var j = 0; flags && j < flagsl; j++) switch (flags.charAt(j)) { case ' ': positivePrefix = ' '; break; case '+': positivePrefix = '+'; break; case '-': leftJustify = true; break; case "'": customPadChar = flags.charAt(j+1); break; case '0': zeroPad = true; break; case '#': prefixBaseX = true; break; } // parameters may be null, undefined, empty-string or real valued // we want to ignore null, undefined and empty-string values if (!minWidth) { minWidth = 0; } else if (minWidth == '*') { minWidth = +a[i++]; } else if (minWidth.charAt(0) == '*') { minWidth = +a[minWidth.slice(1, -1)]; } else { minWidth = +minWidth; } // Note: undocumented perl feature: if (minWidth < 0) { minWidth = -minWidth; leftJustify = true; } if (!isFinite(minWidth)) { throw new Error('sprintf: (minimum-)width must be finite'); } if (!precision) { precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : void(0); } else if (precision == '*') { precision = +a[i++]; } else if (precision.charAt(0) == '*') { precision = +a[precision.slice(1, -1)]; } else { precision = +precision; } // grab value using valueIndex if required? var value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++]; switch (type) { case 's': return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar); case 'c': return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad); case 'b': return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad); case 'o': return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad); case 'x': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad); case 'X': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase(); case 'u': return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad); case 'i': case 'd': { var number = parseInt(+value); var prefix = number < 0 ? '-' : positivePrefix; value = prefix + pad(String(Math.abs(number)), precision, '0', false); return justify(value, prefix, leftJustify, minWidth, zeroPad); } case 'e': case 'E': case 'f': case 'F': case 'g': case 'G': { var number = +value; var prefix = number < 0 ? '-' : positivePrefix; var method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())]; var textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2]; value = prefix + Math.abs(number)[method](precision); return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform](); } default: return substring; } }; return format.replace(regex, doFormat); }
Examples
Currently there are 3 examples
Example 1
sprintf("%01.2f", 123.1);And that would return
123.10Example 2
sprintf("[%10s]", 'monkey');And that would return
'[ monkey]'Example 3
sprintf("[%'#10s]", 'monkey');And that would return
'[####monkey]'More about this Project
Download php.js
To easily include it in your code, every function currently available is stored in
Normal
- uncompressed source: php.js (257.1kB)
- minified: php.min.js (84.4kB) [recommended]
- compressed: php.packed.js (60kB)
Namespaced What is 'namespaced?'
- uncompressed source: php.namespaced.js (317.6kB)
- minified: php.namespaced.min.js (84.7kB)
- compressed: php.namespaced.packed.js (60.4kB)
To download use Right click, Save Link As
Generally the best way is to use a minified version and gzip it
Credits
Respect & awards go to everybody who has contributed in some way so far:



