1.3.0 • Public • Published

    sprintf() lite for JavaScript

    Low-fat implementation of the sprintf() function for JavaScript that gets you all you need.

    For simple string templates:

    {person1} gets easily triggered when {person2} makes fun of CS:GO.

    For easy Swagger and other API spec tools interation as path/route parameters:



    string sprintf (string format [, mixed args [, mixed ... ]])

    format A string that contains the text to be returned, it can optionally contain embedded format specifiers and keys that are replaced by the values specified in subsequent additional arguments and formatted as requested.

    args A number of mixed type arguments for the replacement. Can be a string, array or an object.

    Returns a string produced according to the formatting string merged with replacement values.

    Compatible specifiers

    • %d — print an integer as is
    • %u — print an integer as is
    • %f — print a float as is
    • %s — print a string as is

    Named keys

    • :key - print a value of an object key as is.
    • {key} - print a value of an object key as is.


    npm install sprintf-lite



    var sprintf = require('sprintf-lite').default


    import sprintf from 'sprintf-lite'

    Examples IRL

    Example #1 Basic anonymous keys replacement

    Quick string formatting.

    sprintf('%s + %d = %s', 'Two', 3, 'Five')
    sprintf('/my/%s/api/%s/number/%d', ['awesome', 'endpoint', 1])

    The above example will output:

    Two + 3 = Five

    Example #2 Basic named keys replacement

    Embedding object keys into configuration strings or any string templates.

    sprintf('Dear {firstName} {lastName}, ...', {firstName: 'John', lastName: 'Doe'})
    sprintf('/users/{userId}/orders/{orderId}', {userId: 654321, orderId: 987654321})
    sprintf('/users/:userId/orders/:orderId', {userId: 654321, orderId: 987654321})

    The above example will output:

    Dear John Doe, ...

    Example #3 Argument swapping and reuse

    Keys can be used multiple times in any arbitrary order.

    sprintf('In America, you {do} {what}, in Soviet Russia, {what} {do}s YOU!', {do: 'install', what: 'a package'})

    The above example will output:

    In America, you install a package, in Soviet Russia, a package installs YOU!


    npm i sprintf-lite

    DownloadsWeekly Downloads






    Last publish


    • appmux