sprintf.js
A JavaScript implementation of sprintf, inspired by PHP’s sprintf function. This utility formats strings using placeholders and supports flags, width, precision, and various type specifiers. It’s a self-contained function with no external dependencies, perfect for browser or Node.js environments.
Overview
sprintf parses a format string and replaces placeholders (e.g. %s, %04d, %#x) with corresponding arguments. It supports:
- Padding, justification, and custom pad characters
- Positional arguments (
2$,3$, …) - Variable width and precision (
*,*.2$, …) - Numerical bases: binary, octal, decimal, hexadecimal
- Floating-point formatting: fixed, exponential, general
🚀 Key Features
- PHP-like API: Familiar syntax for PHP developers.
- Flexible flags:
+,-,0, space,#, and custom pad chars via'%. - Precision control: Default precision for floats is 6; can override per placeholder.
- Positional support: Use
%2$sto swap argument order. - Lightweight: Single function, ~100 lines of code.
Usage Examples
sprintf("%01.2f", 123.1); // "123.10"
sprintf("[%10s]", "monkey"); // "[ monkey]"
sprintf("[%'#10s]", "monkey");// "[####monkey]"
| Format | Description | Output |
|---|---|---|
"%01.2f", 123.1 |
Float, width 1, precision 2 | 123.10 |
"[%10s]", "monkey" |
String, width 10, right-pad | [ monkey] |
"[%'#10s]", "monkey" |
String, width 10, pad with # |
[####monkey] |
Core Components
1. Regular Expression Parser
A comprehensive regex splits the format string into tokens:
var regex = /%%|%(\d+\$)?([-+'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;
%%: Escaped percent(\d+\$)?: Positional index([-+'#0 ]*): Flags(\*\d+\$|\*|\d+)?: Minimum width(\.(\*\d+\$|\*|\d+))?: Precision([scboxXuidfegEG]): Type specifier
2. pad(str, len, chr, leftJustify)
Pads a string str to length len with character chr:
function pad(str, len, chr, leftJustify) {
chr = chr || ' ';
var padLen = Math.max(0, len - str.length);
var padding = Array(padLen + 1).join(chr);
return leftJustify ? str + padding : padding + str;
}
- chr: Pad character (default space)
- leftJustify:
trueto append,falseto prepend
3. justify(value, prefix, leftJustify, minWidth, zeroPad, customPadChar)
Applies width and zero-padding around numeric or string values:
function justify(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;
}
- Handles zero-pads after any numeric sign or prefix
- Respects left-justification flag
4. formatBaseX(value, base, prefixFlag, …)
Formats integers in base 2, 8, 10, or 16:
function formatBaseX(value, base, prefixFlag, leftJustify, minWidth, precision, zeroPad) {
var num = value >>> 0;
var prefixMap = {2:'0b', 8:'0', 16:'0x'};
var prefix = prefixFlag && num ? prefixMap[base] : '';
var str = prefix + pad(num.toString(base), precision || 0, '0', false);
return justify(str, prefix, leftJustify, minWidth, zeroPad);
}
- prefixFlag: Adds
0b,0, or0xwhen truthy - precision: Zero-pads number to minimum digits
5. formatString(value, …)
Handles %s and %c formatting:
function formatString(value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
if (precision != null) {
value = value.slice(0, precision);
}
return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
}
- Truncates string to precision
- Pads/truncates to minWidth
6. doFormat(substring, valueIndex, flags, minWidth, _, precision, type)
Main dispatcher that:
- Parses flags (
+,-, space,#,0, custom pad) - Resolves minWidth and precision, including
*and positionaln$ - Retrieves the correct argument (
valueIndexor next inarguments) - Routes to the appropriate formatter based on type specifier
function doFormat(substring, valueIndex, flags, minWidth, _, precision, type) {
if (substring === '%%') return '%';
// parse flags...
// resolve width & precision...
// select value...
switch(type) {
case 's': return formatString(...);
case 'd': // integer
case 'f': // float
case 'x': // hex
// …
default: return substring;
}
}
All placeholders in the format string are replaced via:
return format.replace(regex, doFormat);
Supported Format Specifiers
| Specifier | Description |
|---|---|
%s |
String |
%c |
Character from Unicode code point |
%b |
Binary |
%o |
Octal |
%x/%X |
Hexadecimal (lower/upper case) |
%u |
Unsigned decimal |
%d/%i |
Signed integer |
%e/%E |
Exponential notation (lower/upper case) |
%f/%F |
Floating-point (fixed) |
%g/%G |
General format (uses %e or %f automatically) |
Integration & Dependencies
- Standalone: No imports/exports; defines
sprintfglobally. - Compatibility: Works in browsers and Node.js.
- Use: Include via
<script>tag or require the file in your build.
<script src="js/sprintf.js"></script>
<script>
console.log(sprintf("Hello, %s!", "world"));
</script>
Contributors & Credits
- ✨ Original author: Ash Searle
- 🔧 Namespaced by: Michael White
- 🛠 Tweaks & improvements: Jack, Paulo Freitas, Brett Zamir
- 🚀 Modern enhancements: Kevin van Zonneveld
This utility brings the power of PHP’s sprintf to JavaScript, enabling consistent and powerful string formatting across your application.