UNPKG

6.34 kBMarkdownView Raw
1# sprintf-js
2
3[![Build Status][travisci-image]][travisci-url] [![NPM Version][npm-image]][npm-url] [![Dependency Status][dependencies-image]][dependencies-url] [![devDependency Status][dev-dependencies-image]][dev-dependencies-url]
4
5[travisci-image]: https://travis-ci.org/alexei/sprintf.js.svg?branch=master
6[travisci-url]: https://travis-ci.org/alexei/sprintf.js
7
8[npm-image]: https://badge.fury.io/js/sprintf-js.svg
9[npm-url]: https://badge.fury.io/js/sprintf-js
10
11[dependencies-image]: https://david-dm.org/alexei/sprintf.js.svg
12[dependencies-url]: https://david-dm.org/alexei/sprintf.js
13
14[dev-dependencies-image]: https://david-dm.org/alexei/sprintf.js/dev-status.svg
15[dev-dependencies-url]: https://david-dm.org/alexei/sprintf.js#info=devDependencies
16
17**sprintf-js** is a complete open source JavaScript `sprintf` implementation for the **browser** and **Node.js**.
18
19**Note: as of v1.1.1 you might need some polyfills for older environments. See [Support](#support) section below.**
20
21## Usage
22
23 var sprintf = require('sprintf-js').sprintf,
24 vsprintf = require('sprintf-js').vsprintf
25
26 sprintf('%2$s %3$s a %1$s', 'cracker', 'Polly', 'wants')
27 vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd'])
28
29## Installation
30
31### NPM
32
33 npm install sprintf-js
34
35### Bower
36
37 bower install sprintf
38
39## API
40
41### `sprintf`
42
43Returns a formatted string:
44
45 string sprintf(string format, mixed arg1?, mixed arg2?, ...)
46
47### `vsprintf`
48
49Same as `sprintf` except it takes an array of arguments, rather than a variable number of arguments:
50
51 string vsprintf(string format, array arguments?)
52
53## Format specification
54
55The placeholders in the format string are marked by `%` and are followed by one or more of these elements, in this order:
56
57* An optional number followed by a `$` sign that selects which argument index to use for the value. If not specified, arguments will be placed in the same order as the placeholders in the input string.
58* An optional `+` sign that forces to preceed the result with a plus or minus sign on numeric values. By default, only the `-` sign is used on negative numbers.
59* An optional padding specifier that says what character to use for padding (if specified). Possible values are `0` or any other character precedeed by a `'` (single quote). The default is to pad with *spaces*.
60* An optional `-` sign, that causes `sprintf` to left-align the result of this placeholder. The default is to right-align the result.
61* An optional number, that says how many characters the result should have. If the value to be returned is shorter than this number, the result will be padded. When used with the `j` (JSON) type specifier, the padding length specifies the tab size used for indentation.
62* An optional precision modifier, consisting of a `.` (dot) followed by a number, that says how many digits should be displayed for floating point numbers. When used with the `g` type specifier, it specifies the number of significant digits. When used on a string, it causes the result to be truncated.
63* A type specifier that can be any of:
64 * `%` — yields a literal `%` character
65 * `b` — yields an integer as a binary number
66 * `c` — yields an integer as the character with that ASCII value
67 * `d` or `i` — yields an integer as a signed decimal number
68 * `e` — yields a float using scientific notation
69 * `u` — yields an integer as an unsigned decimal number
70 * `f` — yields a float as is; see notes on precision above
71 * `g` — yields a float as is; see notes on precision above
72 * `o` — yields an integer as an octal number
73 * `s` — yields a string as is
74 * `t` — yields `true` or `false`
75 * `T` — yields the type of the argument<sup><a href="#fn-1" name="fn-ref-1">1</a></sup>
76 * `v` — yields the primitive value of the specified argument
77 * `x` — yields an integer as a hexadecimal number (lower-case)
78 * `X` — yields an integer as a hexadecimal number (upper-case)
79 * `j` — yields a JavaScript object or array as a JSON encoded string
80
81## Features
82
83### Argument swapping
84
85You can also swap the arguments. That is, the order of the placeholders doesn't have to match the order of the arguments. You can do that by simply indicating in the format string which arguments the placeholders refer to:
86
87 sprintf('%2$s %3$s a %1$s', 'cracker', 'Polly', 'wants')
88
89And, of course, you can repeat the placeholders without having to increase the number of arguments.
90
91### Named arguments
92
93Format strings may contain replacement fields rather than positional placeholders. Instead of referring to a certain argument, you can now refer to a certain key within an object. Replacement fields are surrounded by rounded parentheses - `(` and `)` - and begin with a keyword that refers to a key:
94
95 var user = {
96 name: 'Dolly',
97 }
98 sprintf('Hello %(name)s', user) // Hello Dolly
99
100Keywords in replacement fields can be optionally followed by any number of keywords or indexes:
101
102 var users = [
103 {name: 'Dolly'},
104 {name: 'Molly'},
105 {name: 'Polly'},
106 ]
107 sprintf('Hello %(users[0].name)s, %(users[1].name)s and %(users[2].name)s', {users: users}) // Hello Dolly, Molly and Polly
108
109Note: mixing positional and named placeholders is not (yet) supported
110
111### Computed values
112
113You can pass in a function as a dynamic value and it will be invoked (with no arguments) in order to compute the value on the fly.
114
115 sprintf('Current date and time: %s', function() { return new Date().toString() })
116
117### AngularJS
118
119You can use `sprintf` and `vsprintf` (also aliased as `fmt` and `vfmt` respectively) in your AngularJS projects. See `demo/`.
120
121## Support
122
123### Node.js
124
125`sprintf-js` runs in all active Node versions (4.x+).
126
127### Browser
128
129`sprintf-js` should work in all modern browsers. As of v1.1.1, you might need polyfills for the following:
130
131 - `String.prototype.repeat()` (any IE)
132 - `Array.isArray()` (IE < 9)
133 - `Object.create()` (IE < 9)
134
135YMMV
136
137## License
138
139**sprintf-js** is licensed under the terms of the 3-clause BSD license.
140
141## Notes
142
143<small><sup><a href="#fn-ref-1" name="fn-1">1</a></sup> `sprintf` doesn't use the `typeof` operator. As such, the value `null` is a `null`, an array is an `array` (not an `object`), a date value is a `date` etc.</small>