sformat

Fault tolerant console.log style string formatter method.

Usage no npm install needed!

<script type="module">
  import sformat from 'https://cdn.skypack.dev/sformat';
</script>

README

sformat Build Status

Extensible console.log/printf style string formatting.

Installation

npm install sformat --save

Usage

var sformat = require("sformat").create();

// Alternative Construction:
//
// var sformat = require("sformat")();
// var sformat = new require("sformat")();
// var SFormat = require("sformat"); var sformat = new SFormat();

sformat("Hello %s", "World");
// "Hello World"

sformat.args("Hello %s", ["World"]);
// "Hello World"

Specifier Index and Parameters

You can specify the index of the value that a specifier should use, and you can pass parameters to specifier.

The value index is an integer in square [] brackets immediately following the "%" character. An indexed specifier does not consume the value that it references, so non-indexed specifiers can still use the value.

The parameter string is in parentheses () and must follow the index if the index is given.

sformat("%[1](1.3)f %f %f", 1.2, 3.4);
// "3.400 1.2 3.4"

See the individual specifier documentation for parameters supported by a specific specifier.

Escaping a Closing Parenthese

If you must use a closing parenthese ) in the parameter string, you can double it )) to escape it.

sformat("%(6:)))s", "foo");
// ")))foo"
// The string is left padded with a single closing parenthese ) repeated a
// maximum of 6 times.

Default Specifiers

Specifier Description
%% Outputs a literal % character.
%s Formats the value as a string.
%d Formats the value as an integer.
%f Formats the value as a floating point number.
%o Formats the value using Node util.inspect().
%j Formats the value as a JSON string.

%%

Outputs a literal % character.

Parameters

None.

%s

Formats the value as a string.

Parameters

An optional -, followed by an optional padding repeat count, followed by an optional padding string.

  • (-)
    • left aligned
    • no padding character
    • zero padding repeats
    • minimum length of 0 characters (0 * "")
  • (3)
    • right aligned
    • padded with 3 spaces
    • minimum length of 3 characters (3 * " ")
  • (:abc)
    • right aligned
    • padded with "abc"
    • minimum length of 3 characters (1 * "abc")
  • (-3:abc)
    • left aligned
    • padded with "abc" repeated 3 times
    • minimum length of 9 characters (3 * "abc")

No padding is applied and alignment has no effect if neither repeat count or padding string is given.

%d

Formats the value as an integer.

Parameters

An optional +, followed by an optional padded length, followed by an optional parse radix integer, followed by an optional output radix integer, followed by an optional upper case flag.

  • (+)
    • include positive sign prefix for positive numbers
    • no zero padding
    • parsed as a decimal (base 10) number
    • output as a decimal (base 10) number
    • use lowercase letters if the output radix is greater than 10
  • (10)
    • only prefix negative numbers
    • zero padded to at least 10 digits
    • parsed as a decimal (base 10) number
    • output as a decimal (base 10) number
    • use lowercase letters if the output radix is greater than 10
  • (:16)
    • only prefix negative numbers
    • no zero padding
    • parsed as a hexidecimal (base 16) number
    • output as a decimal (base 10) number
    • use lowercase letters if the output radix is greater than 10
  • (/8)
    • only prefix negative numbers
    • no zero padding
    • parsed as a decimal (base 10) number
    • output as an octal (base 8) number
    • use lowercase letters if the output radix is greater than 10
  • (u)
    • only prefix negative numbers
    • no zero padding
    • parsed as a decimal (base 10) number
    • output as a decimal (base 10) number
    • use uppercase letters if the output radix is greater than 10
  • (+10:8/16u)
    • include positive sign prefix for positive numbers
    • zero padded to at least 10 digits
    • parsed as a hexidecimal (base 16) number
    • output as an octal (base 8) number
    • use uppercase letters if the output radix is greater than 10

%f

Formats the value as a floating point number.

Parameters

An optional +, followed by an optional padded length for the integer part, followed by an optional padded length for the fractional part.

  • (+)
    • include positive sign prefix for positive numbers
    • no integer part zero padding
    • no fractional part zero padding
  • (2)
    • only prefix negative numbers
    • integer part zero padded to 2 digits
    • no fractional part zero padding
  • (.3)
    • only prefix negative numbers
    • no integer part zero padding
    • fractional part zeropadded to 3 digits
  • (+2.3)
    • include positive sign prefix for positive numbers
    • integer part zero padded to 2 digits
    • fractional part zeropadded to 3 digits

%o

Formats the value using Node util.inspect().

Parameters

An optional integer number for recursion depth, followed by an optional hidden property flag.

  • (3)
    • recurse 3 times showing the top 4 nested object levels
    • only show enumerable, non-symbol properties.
  • (h)
    • recurse 2 times showing the top 3 nested object levels
    • show hidden (non-enumerable and/or symbol) properties of objects
  • (3h)
    • recurse 3 times showing the top 4 nested object levels
    • show hidden (non-enumerable and/or symbol) properties of objects

%j

Formats the value as a JSON formatted string.

Parameters

An optional integer number of spaces to indent or an indent string.

  • (4)
    • indent JSON using four spaces
  • (\t)
    • indent JSON using a tab character
  • (:4)
    • indent JSON using a literal 4 character
  • (::)
    • indent JSON using a literal : character

If the parameter is entirely numeric, it is assumed to be a number of spaces, unless the parameter string begins with a colon :, in which case everything after the colon is interpreted as an indent string.

Using Arrays of Arguments

To pass replacement values in an array instead of as individual arguments, use the sformat.args method.

sformat.args("%s %s", ["foo", "bar"]);
// "foo bar"

(Re)Defining Format Specifiers

You can use the sformat.define(characters, definition) method to add or redefine format specifiers. The definition parameter can be a function, a specifier string to alias, or false.

If the first argument (characters) is an object, then it's own enumerable properties will be used as a map of definitions. The keys/values will be passed to this method recursively. The key is the characters argument and the value is the definition.

Example: Adding a quoted string specifier.

sformat.define("q", function(getter, params, specifier) {
    // Consume the next value or get the indexed value.
    var value = getter();

    if (value === undefined) {
        // Returning undefined causes the specifier (%q) to be left in the
        // string.
        return;
    } else if (params === "'") {
        return "'" + value.replace(/'/g, "\\'") + "'";
    } else if (params === "" || params === '"') {
        return '"' + value.replace(/"/g, '\\"') + '"';
    } else {
        throw new Error("invalid parameter passed to %q specifier");
    }
});

sformat("%(')q", "foo");
// "'foo'"

Example: Creating a simple alias.

sformat.define("Q", "%q");
sformat("%Q", "foo");
// "\"foo\""
sformat("%(')Q", "foo");
// "'foo'"

Example: Creating an alias with fixed parameters.

sformat.define("Q", "%(')q");
sformat("%Q", "foo");
// "'foo'"
sformat("%(')Q", "foo");
// throws an Error because parameters were included in the alias definition.

Example: Removing the %Q specifier

sformat.define("Q", false);
sformat("%Q", "foo");
// "%Q"

Example: Using a map object to define multiple specifiers at once.

sformat.define({
  "q": function() { ... },
  "Q": "%q"
});

Return Value

If the callback function returns undefined, then the specifier will be left in the output string.

getter function parameter

Indexed

Calling an indexed getter() will return the value at that index without consuming it for next getters.

Next

Calling a next getter() will consume and return the next unconsumed value. Multiple calls gwill not consume more values, but will instead return the same value consumed by the first call.

getter.hasNext

A boolean value indicating that there is at least one more value to get. Calling a getter when there are no more values will return undefined which cannot be distinguished from an actual undefined value having been passed. This flag allows definition functions to distinguish between the two states.

params string parameter

This is the string found between the parentheses () in the specifier, or an empty string if the specifier does not contain parentheses.

specifier string parameter

This is the simplified specifier which is a "%" character followed by the specifier key character.

fullSpecifier string parameter

This is the full specifier string as it occurred in the format string.