StdFormat is a TypeScript/JavaScript library for powerful string formatting using { } notation, inspired by C++20 format and Python format.
There have been few separate npm packages of this project along the line. The recommended and main package is:
std-format 👍 Use this!Other two are kept up to date for legacy support, in case someone is using them:
@sbrockma/std-format@tspro/brace-formatAll three packages are equal and work what is written in this documentation.
IIFE Note: Global name
StdFormatis declared by all three variants.@tspro/brace-formatdeclares additional aliasBraceFormatfor legacy support.
This project is now in maintenance. I will fix bugs and add features on request.
npm i std-format
// Import default export
import StdFormat from "std-format";
StdFormat.format("{}, {}!", "Hello", "world");
// Or import named exports
import { format, int, float, setLocale, FormatError } from "std-format";
format("{}, {}!", "Hello", "world");
const StdFormat = require("std-format");
StdFormat.format("...");
Use the standalone IIFE bundle via unpkg or jsdelivr cdn.
<script src="https://unpkg.com/std-format@4.1.0/dist/index.global.js"></script>
<script src="https://cdn.jsdelivr.net/npm/std-format@4.1.0/dist/index.global.js"></script>
<script>
const { format } = window.StdFormat;
var str = format("{}, {}!", "Hello", "world");
</script>
format(str, ...args)The main formatting function.
format("{}, {}!", "Hello", "world");
int() and float()int() and float() are wrapper functions that can be used to force number to int or float.
format("{}", int(5)); // "5"
format("{}", float(5)); // "5.0"
Note: Formatting rules are strict.
format("{:.2e}", int(5)); // Throws, cannot format int as float.
format("{:d}", float(5)); // Throws, cannot format float as int.
float() simply wraps a number, while int() wraps a JSBI.BigInt, enabling support for large integers.
format("{:d}", int("111111111111111111111111111111"));
You can also pass BigInt to format(), it will be safely wrapped to int().
format("{:d}", BigInt("111111111111111111111111111111"));
setLocale(locale?)Sets the locale for "n" and "L" specifiers:
setLocale("en-GB");
setLocale(); // Reset to default
FormatErrorThrown for formatting violations:
try {
format("{:s}", 42);
}
catch(e) {
if(e instanceof FormatError) {
console.error(e);
}
}
StdFromat uses replacement fields like {}, {0}, {name}, with support for detailed format specs.
{field_id:arr_1:arr_2:arr_N:elem}
field_id: field id/namearr_*: array/object presentationselem: element presentationAny part can be empty string/omitted.
Format specification for element:
[[fill]align][sign]["z"]["#"]["0"][width][grouping]["." precision]["L"][type]
| Part | Description |
|---|---|
fill |
Any char |
align |
<, ^, >, = |
sign |
+, -, space |
z |
Force -0 to +0 |
# |
Alternate form |
0 |
Zero padding |
width |
Width or nested {} |
grouping |
, or _ |
precision |
For floats/strings |
L |
Locale-aware |
type |
See type table below |
Types:
| Type | Description |
|---|---|
| Omitted | Default |
s |
String |
c |
Char (from int) |
d |
Decimal int |
n |
Decimal with locale |
b / B |
Binary |
o |
Octal |
x / X |
Hex |
e / E |
Scientific float |
f / F |
Fixed float |
% |
Percent |
g / G |
General float |
a / A |
Hex float |
Format specification for array, set, map and object:
[[fill]align][width][type]
| Part | Description |
|---|---|
fill |
Any char |
align |
<, ^, > |
width |
Width or nested {} |
type |
See type table below |
Types:
| Type | Output For Array/Set | Output For Map/Object |
|---|---|---|
d / Omitted |
[1, 2, 3] |
[[a, 1], [b, 2], [c, 3]] |
n |
1, 2, 3 |
a: 1, b: 2, c: 3 |
b |
{1, 2, 3} |
{{a, 1}, {b, 2}, {c, 3}} |
m |
[a: 1, b: 2, c: 3] |
|
s |
123 |
a1b2c3 |
// Using auto field numbering
format("{}{}", "A", "B"); // "AB"
// Using manual field numbering
format("{1}{0}", "A", "B"); // "BA"
// Using named fields
format("{name} {age:d}", { name: "Tim", age: 95 }); // "Tim 95"
// Fill, align and width
format("{:0<8d}", 777); // "77700000"
format("{:0^8d}", 777); // "00777000"
format("{:0>8d}", -777); // "0000-777"
format("{:0=8d}", -777); // "-0000777"
// Precision
format("{:.2f}", 1); // "1.00"
// String width
format("{:10.4s}", "Alligator"); // "Alli "
// With nested arguments
format("{:{}.{}s}", "Alligator", 10, 4); // "Alli "
// Array
format("{:d}", [1, 2, 3]); // "[1, 2, 3]"
// Set
format("{:d}", new Set([1, 2, 3, 2])); // "[1, 2, 3]"
// Map
format("{:m:}", new Map([["x", 1], ["y", -1]])); // "[x: 1.0, y: -1.0]"
// Object
format("{{{:n:}}}", { x: 1, y: -1}); // "{x: 1.0, y: -1.0}"
// Floating point types
format("{0:.3e} {0:.3f} {0:.3%} {0:.3g} {0:.3a}", Math.PI); // "3.142e+00 3.142 314.159% 3.14 1.922p+1"
// Integer types
format("{0:#b} {0:#o} {0:#d} {0:#x} {0:c}", 65); // "0b1000001 0o101 65 0x41 A"
Legacy JavaScript has only a single number type, not separate int and float.
// By default format number as float.
format("{}", 5); // "5.0"
// To format number as integer, use type "d".
format("{:d}", 5); // "5"
// Or use int() and float() to force type.
format("{}", int(5)); // "5"
format("{}", float(5)); // "5.0"
This library is written in TypeScript and includes type declarations. Since v3.1.0, it is bundled into ESM, CJS, and IIFE formats using tsup (previously webpack). No changes should be required in the documented usage.
While designed with compatibility in mind, the library has not been explicitly tested against specific Node.js or browser versions.
Found a bug or unexpected behavior?
You can also suggest a feature or impovement.
Thanks for helping improve the project!
This project is licensed under the MIT License.
It also bundles the JSBI library, which is licensed under the Apache License 2.0.