sprintf.js
A standalone JavaScript implementation of C-style sprintf formatting. It parses a format string and replaces conversion specifiers with provided values.
Overview
A single function, sprintf(), that mimics PHP/Perl/C printf behavior.
- Supports positional arguments, flags, width, precision, and various type specifiers.
- No external dependencies; pure ES5 JavaScript.
Key Features
- 🎯 C-style specifiers:
%d,%f,%s,%x, etc. - 🔢 Positional parameters:
%2$spicks the second argument as a string. - 🎛️ Flags: left-justify, sign, zero-pad, prefix, custom pad.
- 📏 Width & Precision: dynamic (
*) or static values. - 🔄 Base conversion: binary, octal, decimal, hexadecimal.
Usage Examples
sprintf("%01.2f", 123.1); // "123.10"
sprintf("[%10s]", "monkey"); // "[ monkey]"
sprintf("[%'#10s]", "monkey"); // "[####monkey]"
sprintf("%2$04d %1$s", "hi", 5); // "0005 hi"
Format Specifier Syntax
Every conversion specifier follows this pattern:
%[argIndex$][flags][width][.precision]type
| Component | Description |
|---|---|
| argIndex$ | (Optional) 1-based index to pick a specific argument. |
| flags | - + 0 # space 'paddingChar (see Flags section) |
| width | Minimum field width (number, * for dynamic, or *n$ for positional dynamic). |
| .precision | Precision for float or maximum string length (.number, .*, or .*n$). |
| type | One of s, c, b, o, x, X, u, i, d, e, E, f, F, g, G, %. |
Flags
| Flag | Description |
|---|---|
- |
Left-justify the result within the given field width. |
+ |
Always prefix numeric output with a sign (+ or -). |
| (space) | Prefix positive numbers with a space. |
0 |
Zero-pad numeric output instead of space-padding. |
# |
Alternate form: add prefixes (0, 0b, 0x) for octal, binary, hex. |
'x |
Use character x as padding. |
Supported Types
| Type | Description |
|---|---|
| s | String |
| c | Character (from char code) |
| b/o/x/X/u | Unsigned integer in binary/octal/hex (lower/upper)/decimal |
| d/i | Signed integer |
| e/E | Scientific notation (lower/upper) |
| f/F | Fixed-point notation (lower/upper) |
| g/G | Shortest representation (lower/upper) |
| % | Literal percent sign % |
Internal Architecture
1. Regular Expression
A global regex splits the format string into literals and specifiers:
var regex = /%%|%(\d+\$)?([-+'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;
- Matches
%%or full specifiers. - Captures argument index, flags, width, precision, and type.
2. pad()
Pads a string to a given length with a character.
function pad(str, len, chr=' ', leftJustify) {
var padLen = len - str.length;
var fill = padLen>0 ? Array(padLen+1).join(chr) : '';
return leftJustify ? str+fill : fill+str;
}
3. justify()
Applies left/right justification and zero-padding:
function justify(value, prefix, leftJustify, minWidth, zeroPad, customPadChar) { … }
4. formatBaseX()
Converts numbers to binary/octal/hex with optional prefix:
function formatBaseX(value, base, prefixFlag, leftJustify, minWidth, precision, zeroPad) { … }
5. formatString()
Handles string truncation (precision) and padding:
function formatString(value, leftJustify, minWidth, precision, zeroPad, customPadChar) { … }
6. doFormat()
Core formatter invoked per specifier. It:
- Parses flags and parameters.
- Fetches the correct argument.
- Delegates to the helper above based on the type.
- Returns the formatted substring.
Integration
- Simply include
sprintf.jsin your project. - It exposes a global
sprintffunction. - To use in Node.js, wrap with:
module.exports = sprintf; - No installation steps or dependencies required.
Design Considerations
- ✅ Pure ES5: Works in old and modern environments.
- 🎯 Single-responsibility: One file, one function.
- 🔄 Extensible: You can override or extend helper functions.
- ⚡ Performance: Regex-driven parsing for efficiency.
Credits: Adapted from original work by Ash Searle, Michael White, Kevin van Zonneveld, and others.