1.2.5 • Published 4 years ago

template-format v1.2.5

Weekly downloads
4,938
License
ISC
Repository
github
Last release
4 years ago

template-format

Simple string formatting with support for nested data.

Install

npm install template-format

Syntax

const formattedText = format(text, data, options={})
ParameterTypeDefaultDescription
textstringText to format
objectobjectThe object or array containing the data to be used for formatting.
optionsobject{}Optional Extra options, read below.
options.regexregex/{(.*?)}/gOptional Alternative regex for different format syntaxes (i.e.: Hello {{name}}!). Must include the global match modifier (g).
options.skipUndefinedobjectfalseOptional Skips formatting parameters which are missing in the object, keeping the original text. Otherwise they'll be replaced by an empty string.
options.spreadTokenstring$nOptional Token used on arrays to indicate that the following attributes have to be applied in each element (See example below).
options.spreadSeparatorstring,Optional String used on arrays to separate of the formatting in each element.

Usage

import format from 'template-format'

With objects

format('Hello {name}, happy {age} bday!', { name: 'Bob', age: 32 })
// 'Hello Bob, happy 32 bday!'

With arrays

format('Hello {0}, happy {1} bday!', ['Bob', 32])
// 'Hello Bob, happy 32 bday!'

With nested data

format('Hello {bob.name}, happy {bob.age} bday! I call you at {bob.contact.phone}', {
        bob: {
            name: 'Bob', 
            age: 32, 
            contact: {
                phone: '978090909'
            }
        }
    })
// 'Hello Bob, happy 32 bday! I call you at 978090909'

Spread arrays

format('Hello {people.$n.name}!', { people: [{ name: 'Bob' }, { name: 'Mary' }] })
// 'Hello Bob,Mary!'

Other Options

  • Skip undefined attributes:
format('Hello {name}, happy {age} bday!', { name: 'Bob' })
// 'Hello Bob, happy bday!'
format('Hello {name}, happy {age} bday!', { name: 'Bob' }, { skipUndefined: true })
// 'Hello Bob, happy {age} bday!'
  • Using a different format syntax:
format('Hello {{name}}, happy {{age}} bday!', { name: 'Bob', age: 32}, { regex: /{{(.*?)}}/g })
// 'Hello Bob, happy 32 bday!'
  • Custom spreading
format('Hello {people.$$.name}!', { people: [{ name: 'Bob' }, { name: 'Mary' }] }, { spreadToken: '$$', spreadSeparator: ', ' })
// 'Hello Bob, Mary!'

Changelog

  • 1.2.0

    • Support to spread formatting on arrays
    • Customizable spreading with spreadToken and spreadSeparator
  • 1.1.0

    • Support to skip undefined attributes
    • Support for alternative format syntaxes
  • 1.0.0

    • Initial release :tada:

License

ISC License

1.2.5

4 years ago

1.2.4

5 years ago

1.2.3

5 years ago

1.2.2

5 years ago

1.2.1

5 years ago

1.2.0

6 years ago

1.1.0

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago