npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

string-format

v2.0.0

Published

String formatting inspired by Python's str.format()

Downloads

2,080,730

Readme

string-format

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

'"{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!'

const restaurant = {name: 'Anchor & Hope', url: 'http://anchorandhopesf.com/'}

fmt('<a href="{url!escape}">{name!escape}</a>', restaurant)
// => '<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!'

const restaurant = {name: 'Anchor & Hope', url: 'http://anchorandhopesf.com/'}

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

Running the test suite

$ npm install
$ npm test