• Stars
    star
    332
  • Rank 126,957 (Top 3 %)
  • Language
    JavaScript
  • License
    Do What The F*ck ...
  • Created about 12 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

JavaScript string formatting inspired by Python’s `str.format()`

string-format

string-format is a small JavaScript library for formatting strings, based on Python's str.format(). For example:

> const user = {
.   firstName: 'Jane',
.   lastName: 'Smith',
.   email: '[email protected]',
. }
> '"{firstName} {lastName}" <{email}>'.format (user)
'"Jane Smith" <[email protected]>'

The equivalent concatenation:

> '"' + user.firstName + ' ' + user.lastName + '" <' + user.email + '>'
'"Jane Smith" <[email protected]>'

Installation

Node

  1. Install:

    $ npm install string-format
  2. Require:

    const format = require ('string-format')

Browser

  1. Define window.format:

    <script src="path/to/string-format.js"></script>

Modes

string-format can be used in two modes: function mode and method mode.

Function mode

> format ('Hello, {}!', 'Alice')
'Hello, Alice!'

In this mode the first argument is a template string and the remaining arguments are values to be interpolated.

Method mode

> 'Hello, {}!'.format ('Alice')
'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.extend (String.prototype, {})

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}'.format ('Holly', 2, 's')
'Holly, you have 2 unread messages'

Unmatched placeholders produce no output:

> '{0}, you have {1} unread message{2}'.format ('Steve', 1)
'Steve, you have 1 unread message'

A format string may reference a positional argument multiple times:

> "The name's {1}. {0} {1}.".format ('James', 'Bond')
"The name's Bond. James Bond."

Positional arguments may be referenced implicitly:

> '{}, you have {} unread message{}'.format ('Steve', 1)
'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}?'.format ('Lemony', 'Snicket')
! ValueError: cannot switch from implicit to explicit numbering

{{ and }} in format strings produce { and }:

> '{{}} creates an empty {} in {}'.format ('dictionary', 'Python')
'{} 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}'.format (bobby, garry)
'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}'.format (repo)
'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: new Date ('1970-01-01'),
.   fullName: function() { return this.firstName + ' ' + this.lastName },
.   quip: function() { return 'Bazinga!' },
. }

> '{fullName} was born at precisely {dob.toISOString}'.format (sheldon)
'Sheldon Cooper was born at precisely 1970-01-01T00:00:00.000Z'

> "I've always wanted to go to a goth club. {quip.toUpperCase}".format (sheldon)
"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.create ({
.   escape: s =>
.     s.replace (/[&<>"'`]/g, c => '&#' + c.charCodeAt (0) + ';'),
.   upper: s =>
.     s.toUpperCase (),
. })

> fmt ('Hello, {!upper}!', 'Alice')
'Hello, ALICE!'

> fmt ('<a href="{url!escape}">{name!escape}</a>', {
.   name: 'Anchor & Hope',
.   url: 'http://anchorandhopesf.com/',
. })
'<a href="http://anchorandhopesf.com/">Anchor &#38; 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.extend (String.prototype, {
.   escape: s =>
.     s.replace (/[&<>"'`]/g, c => '&#' + c.charCodeAt (0) + ';'),
.   upper: s =>
.     s.toUpperCase (),
. })

> 'Hello, {!upper}!'.format ('Alice')
'Hello, ALICE!'

> '<a href="{url!escape}">{name!escape}</a>'.format ({
.   name: 'Anchor & Hope',
.   url: 'http://anchorandhopesf.com/',
. })
'<a href="http://anchorandhopesf.com/">Anchor &#38; Hope</a>'

Running the test suite

$ npm install
$ npm test

More Repositories

1

Base64.js

Polyfill for browsers that don't provide window.btoa and window.atob
JavaScript
489
star
2

doctest

Doctests for JavaScript (and CoffeeScript)
JavaScript
165
star
3

tutor

JavaScript interface for the Gatherer card database
CoffeeScript
149
star
4

xyz

Publish npm packages with fewer screw-ups
Shell
101
star
5

transcribe

📝 Generate Markdown documentation from code comments
JavaScript
79
star
6

an.hour.ago

A small utility which enables wonderfully expressive date and time manipulation in JavaScript
CoffeeScript
69
star
7

nucleotides

The building blocks of JavaScript programs
JavaScript
32
star
8

airwaves

Broadcast on a dedicated frequency
CoffeeScript
25
star
9

mathmethods

A tiny script which makes methods of the `Math` object available to numbers by adding properties to `Number.prototype`
CoffeeScript
17
star
10

orthogonal

DSL for describing simple vector graphics
CoffeeScript
14
star
11

CANON

Canonical object notation
JavaScript
12
star
12

jQuery.localize

⌚ jQuery plugin for localizing dates and times via the `datetime` attribute of the HTML5 `<time>` element
JavaScript
8
star
13

hex2xterm

🌈 Convert hexadecimal colour codes to xterm colour codes
JavaScript
3
star
14

fp-workshop

FP workshop presented at HolidayCheck in Munich on 2016-12-14
JavaScript
3
star
15

remember-bower

🐦 Never forget to update dependencies in bower.json again
JavaScript
2
star
16

cube

Magic: The Gathering Cube
HTML
2
star
17

deedpoll

📄 Flag incorrectly named identifiers in JavaScript programs
Shell
2
star
18

contenteditable

A jQuery utility which adds useful behaviour to `contenteditable` text
CoffeeScript
2
star
19

rich

JavaScript’s missing stdlib
1
star
20

davidchambersdesign.com

1
star
21

Homelands-Constructed

Lists from a terrific Homelands Constructed tournament held in Auckland on 27/12/2011
1
star
22

got-lambda

Repository used during Got.λ presentation on 1 September 2016
JavaScript
1
star