Simple utility for formatting string messages. If a single object is passed it is converted to string using node's util.inspect. When string format tokens are present e.g. %s, %d, %j and so on the string is formatted using node's util.format. For more advanced formatting you can use templating which allows piping values in order through custom transform handlers. Kind of similar to Angular's early pipes.
$ npm install formatr
Import the module.
import * as formatr from 'formatr';
// OR
const formatr = require('formatr');
let result = formatr.format({ category: 'Movies', title: 'Office Space' });
// util.inspect converts object to string.
result = "{ category: 'Movies', title: 'Office Space' }"
let result = formatr.format('The movie %s was released in %d', 'Office Space', 1999);
// util.format maps args to tokens.
result = 'The movie Office Space was released in 1999'
const obj = { name: 'Milton Waddams', stapler: 'Swingline' };
let result = formatr.format('My name is {{ name }} and I want my {{ stapler }} stapler.', obj);
// template formatter maps object values.
result = 'My name is Milton Waddams and I want my Swingline stapler.'
// Add custom transform for quotes.
formatr.setOption('transforms.quote', (v) => `"${v}"`);
const obj = { name: 'milton waddams', stapler: 'swingline' };
let result = formatr.format('My name is {{ name|titlecase|quote }} and I want my {{ stapler|capitalize }} stapler.', obj);
// values are mapped from object name is titlecased and wrapped in quotes.
result = 'My name is "Milton Waddams" and I want my Swingline stapler.'
Please refer to docs for more details but here are the basics.
When using templating ONLY this is the default value when undefined is returned.
Name | default |
Type | string |
Default | '' |
This property is passed to util.inspect when formatting objects.
Name | colorize |
Type | boolean |
Default | false |
This property is passed to util.inspect when formatting objects.
Name | hidden |
Type | boolean |
Default | null |
This property is passed to util.inspect when formatting objects.
Name | depth |
Type | number |
Default | null |
When using template formatting this is the RegExp for parsing templates.
Name | exp |
Type | RegExp |
Default | /{{([\s\S]+?)}}/g |
When using template formatting this is the RegExp for stripping parsed templates.
Name | strip |
Type | RegExp |
Default | /[{}]+/g |
When using template formatting this character used to split transforms.
Name | split |
Type | string |
Default | | |
When using template formatting this is a handler run on each value after getting from format object.
Name | transform |
Type | function |
Signature | (val?: any, key?: string, obj?: object) |
Default | undefined |
When using template formatting this an object of built in transforms.
Name | transforms |
Type | object |
Default | capitalize, lowercase, uppercase, camelcase, titlecase |
See https://blujedis.github.io/formatr/
See CHANGE.md
See LICENSE.md
Generated using TypeDoc