npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

custom-string-formatter

v1.2.1

Published

Customizable String Formatter

Downloads

128

Readme

custom-string-formatter

ci Node Version

Replaces variables in a string, using your own value formatting.

The variable syntax supports:

  • nested properties
  • filters chaining / pipeline
  • filter arguments

${prop1.prop2.prop3 | filter1 | filter2 | filter3 : arg1 : arg2}

Basic Use:

import {createFormatter, IFormatter} from 'custom-string-formatter';

class BaseFormatter implements IFormatter {
    format(value: any): string {
        // your own value formatting here;
        return (value ?? 'null').toString();
    }
}

// creating a reusable formatting function:
const format = createFormatter(new BaseFormatter());

// formatting a string with values from an object:
const s = format('Hello ${title} ${name}!', {title: 'Mr.', name: 'Foreman'});

console.log(s); //=> Hello Mr. Foreman!

And because the above is based on interfaces, you can simplify it to just:

const format = createFormatter({
    format: (value: any) => (value ?? 'null').toString()
});

Installation

$ npm i custom-string-formatter

Current GitHub CI is set up for just NodeJS v18-v24, but it works in all browsers the same.

Variable Syntax

Basic variable syntax is as below:

  • ${propertyName}
  • $(propertyName)
  • $<propertyName>

The extra syntax is for cases like combining it with ES6 Template Literals, etc.

Property names follow a simple JavaScript variable notation: the name can contain letters (case-sensitive), digits, $, _ (underscore) and . for nested properties. For array access, like prop[123].value, use prop.123.value syntax instead, for the fastest possible value resolution that avoids performance-expensive property tokenization.

You can use a combination of the above inside one string, but you cannot combine opener-closer pairs, i.e. something like ${propertyName) is invalid, and won't be recognized as a variable.

Full Syntax:

Full variable syntax supports a chain of nested properties, plus optional filters with arguments:

  • ${prop1.prop2.prop3 | filter1 | filter2 | filter3 : arg1 : arg2}.

All spaces in between are ignored, i.e. ${ prop | filter : arg } works the same as ${prop|filter:arg}.

See the chapters below for further details.

Formatting Filters

Formatting filters can be appended to the property name after | separator, for value transformation, in the form of ${propertyName | filter1 | filter2 | filter3}.

Filter names follow a simple JavaScript variable notation: the name can contain letters (case-sensitive), digits, $ and _ (underscore).

Filters perform value transformation in the same order in which they are specified, as a pipeline, with the output from the last filter going to the formatter, to be converted into a string (if needed).

Example of using formatting filters:

import {createFormatter, IFormatter, IFilter} from 'custom-string-formatter';
import dayjs from 'dayjs';

class JsonFilter implements IFilter {
    transform(value: any): any {
        return JSON.stringify(value); // transform into a JSON string
    }
}

type DateInput = Date | number | string; // inputs that dayjs supports

class DateFilter implements IFilter<DateInput, string> {
    transform(value: DateInput, args: string[]): string {
        return dayjs(value).format(args[0]); // use dayjs to format the date
    }
}

class BaseFormatter implements IFormatter {
    format(value: any): string {
        return (value ?? 'null').toString();
    }

    // name->object map of all our filters:
    filters = {
        date: new DateFilter(),
        json: new JsonFilter()
    };
}

const format = createFormatter(new BaseFormatter());

const s = format('${title} ${name} address: ${address | json}, updated: ${updated | date : DD-MM-YYYY}', {
    title: 'Mr.',
    name: 'Foreman',
    address: {street: 'Springfield', house: 10},
    updated: new Date()
});

console.log(s); //=> Mr. Foreman address: {"street":"Springfield","house":10}, updated: 09-11-2025

For more, see Examples in the WiKi.

Filter Arguments

You can pass optional arguments into a filter after : symbol:

${propertyName | filterName : -123.45 : Hello World!}

For the example above, method transform will receive args set to ['-123.45', 'Hello World!'].

Passing in empty arguments like filter:::Hello World! or filter : : : Hello World! will produce a list of arguments set to ['', '', 'Hello World!'].

IMPORTANT

Filter arguments cannot contain symbols |:{}<>(), as they would conflict with the variable syntax. To pass those in, you need to sanitize them (HTML-encode), as shown below.

Filter arguments are automatically HTML-decoded (unless decodeArguments override is present):

  • &#8364; => : decimal symbol codes (1–6 digits)
  • &#x1F60a; => 😊: hexadecimal symbol codes (1–5 hex digits, case-insensitive)

| symbol | decimal | hexadecimal | |:------:|:--------:|:-----------:| | \| | &#124; | &#x7c; | | : | &#58; | &#x3a; | | { | &#123; | &#x7b; | | } | &#125; | &#x7d; | | < | &#60; | &#x3c; | | > | &#62; | &#x3e; | | ( | &#40; | &#x28; | | ) | &#41; | &#x29; |


You can use function sanitizeFilterArgs to encode all such special symbols automatically. For manual conversion, use the table above or check out the online helper.

You can also override method decodeArguments, for the following purposes:

  • to let the filter control individual argument decoding
  • to optimize the filter's performance by not decoding some or all arguments
  • to also remove accents (diacritical marks), supported by decodeFilterArg

Self-Reference

When a property chain starts with this (case-sensitive), the parser treats it as the reference to the parameter object itself. It is to avoid wrapping the parameter object into another object when you want to format that parameter object itself.

For the above example with the filter, we can use it like this:

const s = format('Address: ${this | json}', {street: 'Springfield', house: 10});

console.log(s); //=> Address: {"street":"Springfield","house":10}

Above, we referenced the parameter object itself, and then forwarded formatting into our json filter.

Because this references the parameter object, its use with nested properties is also valid - ${this.prop1.prop2}, though it may not have a practical need (use of this in this case is superfluous), but just for logical consistency.

Input Analysis

If you need to verify an input string for the variable references it has, this library offers three global functions to help you with that:

| Function | Description | |------------------|-----------------------------------------------------| | hasVariables | A fast check if a string has valid variables in it. | | countVariables | A fast count of valid variables in a string. | | enumVariables | Enumerates and parses variables from a string. |

Example:

import {enumVariables} from 'custom-string-formatter';

enumVariables('${title} ${name} address: ${address | json}');
// ==>
[
    {match: '${title}', property: 'title', filters: []},
    {match: '${name}', property: 'name', filters: []},
    {
        match: '${address | json}',
        property: 'address',
        filters: [{name: 'json', args: []}]
    }
]

Safety Checks

Property-name Safety

The parser requires that any referenced property exists, or else it will throw Property "propName" does not exist. This is to help with detection of invalid property names.

If a property is missing, it must be set to undefined before it can be referenced from a string, to avoid the error.

You can override such behavior by implementing getDefaultValue function inside IFormatter and return a default value whenever the property cannot be resolved. This is, however, not the safest approach when no error is thrown, as invalid property names can be easily missed.

Filter-name Safety

When using an unknown filter, the parser will throw Filter "filterName" not recognized, to help with detection of invalid filter names.

You can override such behavior by implementing getDefaultFilter function inside IFormatter and return an alternative filter. This can have various uses, such as:

  • Support for filter aliases
  • Support for dynamic filters / lazy-loading

Check out the examples.

Performance

The high performance of this library is enforced right in the unit tests ( see ./test/performance.spec.ts).

The engine can replace over one million variables per second. It is faster than most alternatives out there, which make use of performance-expensive property tokenization.

Tested under NodeJS v18/24.