string-format
string-format is a small JavaScript library for formatting strings, based on
Python's str.format()
. For example:
'"{firstName} {lastName}" <{email}>'// => '"Jane Smith" <jsmith@example.com>'
The equivalent concatenation:
'"' + userfirstName + ' ' + userlastName + '" <' + useremail + '>'// => '"Jane Smith" <jsmith@example.com>'
Installation
Node
-
Install:
$ npm install string-format -
Require:
const format =
Browser
-
Define
window.format
:
Modes
string-format can be used in two modes: function mode and method mode.
Function mode
// => 'Hello, Alice!'
In this mode the first argument is a template string and the remaining arguments are values to be interpolated.
Method mode
'Hello, {}!'// => 'Hello, Alice!'
In this mode values to be interpolated are supplied to the format
method
of a template string. This mode is not enabled by default. The method must
first be defined via format.extend
:
format
format(template, $0, $1, …, $N)
and template.format($0, $1, …, $N)
can then
be used interchangeably.
format(template, $0, $1, …, $N)
Returns the result of replacing each {…}
placeholder in the template string
with its corresponding replacement.
Placeholders may contain numbers which refer to positional arguments:
'{0}, you have {1} unread message{2}'// => 'Holly, you have 2 unread messages'
Unmatched placeholders produce no output:
'{0}, you have {1} unread message{2}'// => 'Steve, you have 1 unread message'
A format string may reference a positional argument multiple times:
"The name's {1}. {0} {1}."// => "The name's Bond. James Bond."
Positional arguments may be referenced implicitly:
'{}, you have {} unread message{}'// => 'Steve, you have 1 unread message'
A format string must not contain both implicit and explicit references:
'My name is {} {}. Do you like the name {0}?'// => ValueError: cannot switch from implicit to explicit numbering
{{
and }}
in format strings produce {
and }
:
'{{}} creates an empty {} in {}'// => '{} creates an empty dictionary in Python'
Dot notation may be used to reference object properties:
const bobby = firstName: 'Bobby' lastName: 'Fischer'const garry = firstName: 'Garry' lastName: 'Kasparov' '{0.firstName} {0.lastName} vs. {1.firstName} {1.lastName}'// => 'Bobby Fischer vs. Garry Kasparov'
0.
may be omitted when referencing a property of {0}
:
const repo = owner: 'davidchambers' slug: 'string-format' 'https://github.com/{owner}/{slug}'// => 'https://github.com/davidchambers/string-format'
If the referenced property is a method, it is invoked with no arguments to determine the replacement:
const sheldon = firstName: 'Sheldon' lastName: 'Cooper' dob: '1970-01-01' { return thisfirstName + ' ' + thislastName } { return 'Bazinga!' } '{fullName} was born at precisely {dob.toISOString}'// => 'Sheldon Cooper was born at precisely 1970-01-01T00:00:00.000Z' "I've always wanted to go to a goth club. {quip.toUpperCase}"// => "I've always wanted to go to a goth club. BAZINGA!"
format.create(transformers)
This function takes an object mapping names to transformers and returns a
formatting function. A transformer is applied if its name appears, prefixed
with !
, after a field name in a template string.
const fmt = format // => 'Hello, ALICE!' const restaurant = name: 'Anchor & Hope' url: 'http://anchorandhopesf.com/' // => '<a href="http://anchorandhopesf.com/">Anchor & Hope</a>'
format.extend(prototype, transformers)
This function takes a prototype (presumably String.prototype
) and an object
mapping names to transformers, and defines a format
method on the prototype.
A transformer is applied if its name appears, prefixed with !
, after a field
name in a template string.
format 'Hello, {!upper}!'// => 'Hello, ALICE!' const restaurant = name: 'Anchor & Hope' url: 'http://anchorandhopesf.com/' '<a href="{url!escape}">{name!escape}</a>'// => '<a href="http://anchorandhopesf.com/">Anchor & Hope</a>'
Running the test suite
$ npm install$ npm test