string_format
A small JavaScript library for formatting strings. It's inspired by and modelled on Python's
str.format()
.
When format
is invoked on a string, placeholders within the string are
replaced with values determined by the arguments provided. A placeholder
is a sequence of characters beginning with {
and ending with }
.
Install
npm install string_format
Synopsys
Examples
For more examples see test page
Usage
;
General
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 messageundefined'
A format string may reference a positional argument multiple times:
'{0} x {0} x {0} = {1}';// '3 x 3 x 3 = 27'
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:
var bobby = first_name: 'Bobby' last_name: 'Fischer'; var garry = first_name: 'Garry' last_name: 'Kasparov'; '{0.first_name} {0.last_name} vs. {1.first_name} {1.last_name}'// 'Bobby Fischer vs. Garry Kasparov'
When referencing the first positional argument, 0.
may be omitted:
var repo = owner : 'pypy' slug : 'pypy' followers: 1 2 3; '{owner}/{slug} has {followers.length} followers';// 'pypy/pypy has 3 followers'
If the referenced property is a method, it is invoked and the result is used as the replacement string:
var me = name: 'David' dob: ; '{name} was born in {dob.getFullYear}';// 'David was born in 2015' '{pop}';// three
Arrays
'{0[1]}'; // 1 '{0["0"]}'); // 1 '{0[1]} {1[1]}');// 1 2 '{0[1][1][1]}';// 3 '{0[1]()}'); // 1 '{0[1](1)[1][1]}';// 1 '{0[1](1)[1][1]}:{1[1][1][1]}:{2}:{3.method[1]}';// 1:3:2:1
Escaping
'{{'; // { '{{}}';// {} '{{{0}}}';// {123}
Functions
'{0}';// 1 '.format(function () { return 1;});// 1 ''.format( function () { return 1; }, function () { return 1; });// 11 ''.format(function (value) { return value;});// 1 ''.format(function () { return function () { return 1; };});// 1 '211:1'.format(function (a) { return function (b) { return [0, [1, a + b]]; };}, 1); // 3:1
Methods
'{0.method[1]}';// 1 '{method(1)}';// 1 '{object.method(1, 2)}'; // 3 '{0.method[0]()}';// 1 '{0.method[0](1)}';// 1 '{object.method[1]} + {object2.method[1]} = 2';// 1 + 1 = 2 '{0.method(1, 2)}';// 3 '{0.method(1, 2)(3, 4)}'; // 10 '{0.method(0)(1)[0][1](1, 2)}'; // 4
Undefined values
'{0}';// null '{0}';// undefined
Tests
npm test