Skip to content

b4dnewz/string-template

Repository files navigation

string-template

A utility to format strings with many options

NPM version Build Status Coverage percentage

Getting started

Download it using your favourite package manager.

npm i @b4dnewz/string-template

Then import it in your code and have fun formatting strings.

import template from "@b4dnewz/string-template";

const str = `
    That's an awfully hot {item},
    did {person} kill himself?
    Probably {answer}.
`;

template(str, {
    item: "coffee pot",
    person: "Jeffrey Epstein",
    answer: "not"
});

By default the function will fail if unknown properties are found, but can be disabled using options.

Using custom pattern

The string template function will use this pattern {%s}, for finding variables in the string, where %s will be replaced with the built-in word match pattern which is not customizable.

If you want to use a different template pattern you can add the pattern option as third parameter.

const str = `Using a <:adjective:> pattern`;

const out = template(str, {
    adjective: "different"
}, {
    pattern: "<:%s:>"
});

console.log(out);

Options

pattern

Type: string

The string template pattern to use for finding replacements, it must use the string replacer %s to know where to put the word pattern.

template(input, replacements, {
    pattern: ":%s:"
});

ignoreErrors

Type: boolean

When true unknown properties in the string will not raise an error and will simply ignored.

template(input, replacements, {
    ignoreErrors: true
});

License

This package is released under MIT License © Filippo Conti