Formatter

The Formatter class allows you to format messages by replacing placeholders with values from an object. It supports nested placeholders, callbacks, and custom markers. The class is part of the Monster.Text module.

Installation

npm install @schukai/monster

Usage

import {Formatter} from '@schukai/monster/source/text/formatter.mjs';

Basic Usage

Create an instance of the Formatter class by passing an object containing the values to be used for formatting. Then, call the format method with a string containing placeholders.

const formatter = new Formatter({
    key: 'value',
    nested: {
        key: 'nested value',
    },
});

const formattedText = formatter.format('This is a ${key} and this is a ${nested.key}');
console.log(formattedText); // Output: "This is a value and this is a nested value"

Nested Placeholders

Placeholders can be nested, allowing you to use the value of an inner placeholder as a key for an outer placeholder.

const text = '${mykey${subkey}}';
const obj = {
    mykey2: '1',
    subkey: '2',
};

const formatter = new Formatter(obj);
console.log(formatter.format(text)); // Output: "1"

Callbacks

You can adjust the values in a formatter using callbacks.

const formatter = new Formatter({x: '1'}, {
    callbacks: {
        quote: (value) => {
            return '"' + value + '"';
        },
    },
});

console.log(formatter.format('${x | call:quote}')); // Output: "\"1\""

Custom Markers

You can customize the markers for the placeholders by calling the setMarker method.


formatter.setMarker('#'); // both open and close markers are #
formatter.setMarker('[', ']');
formatter.setMarker('i18n{', '}');