
Security News
Django Joins curl in Pushing Back on AI Slop Security Reports
Django has updated its security policies to reject AI-generated vulnerability reports that include fabricated or unverifiable content.
string-format
Advanced tools
Adds a `format` method to `String.prototype`. Inspired by Python's `str.format()`.
The string-format npm package is a utility for formatting strings in a variety of ways. It allows you to insert values into placeholders within a string, making it easier to create dynamic and readable strings.
Basic Formatting
This feature allows you to insert values into placeholders within a string. The placeholders are denoted by curly braces {}.
const format = require('string-format');
const result = format('Hello, {}!', 'World');
console.log(result); // Output: Hello, World!
Named Placeholders
Named placeholders allow you to use keys from an object to insert values into the string. This makes the code more readable and easier to manage.
const format = require('string-format');
const result = format('Hello, {name}!', { name: 'Alice' });
console.log(result); // Output: Hello, Alice!
Indexed Placeholders
Indexed placeholders use numerical indices to insert values into the string. This is useful when you have an array of values to insert.
const format = require('string-format');
const result = format('Hello, {0} {1}!', 'John', 'Doe');
console.log(result); // Output: Hello, John Doe!
The sprintf-js package provides a similar functionality to string-format but follows the sprintf syntax commonly used in C. It offers more advanced formatting options, such as padding and precision control.
The util.format function is a built-in Node.js utility that provides basic string formatting capabilities. It is less feature-rich compared to string-format but is sufficient for simple use cases.
The lodash.template function from the lodash library offers a more powerful and flexible templating system. It supports custom delimiters and more complex logic within the templates, making it suitable for more advanced use cases.
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" <jsmith@example.com>'
The equivalent concatenation:
'"' + user.firstName + ' ' + user.lastName + '" <' + user.email + '>'
// => '"Jane Smith" <jsmith@example.com>'
Install:
$ npm install string-format
Require:
var format = require('string-format')
Define window.format
:
<script src="path/to/string-format.js"></script>
String::format can be used in two modes: function mode and method 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.
'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:
var bobby = {firstName: 'Bobby', lastName: 'Fischer'}
var 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}
:
var 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:
var sheldon = {
firstName: 'Sheldon',
lastName: 'Cooper',
dob: new Date('1970-01-01'),
fullName: function() { return '{firstName} {lastName}'.format(this) },
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.extend(prototype[, transformers])
This function defines a format
method on the provided prototype (presumably
String.prototype
). One may provide an object mapping names to transformers.
A transformer is applied if its name appears, prefixed with !
, after a field
name in a template string.
format.extend(String.prototype, {
escape: function(s) {
return s.replace(/[&<>"'`]/g, function(c) {
return '&#' + c.charCodeAt(0) + ';'
})
},
upper: function(s) { return s.toUpperCase() }
})
'Hello, {!upper}!'.format('Alice')
// => 'Hello, ALICE!'
var restaurant = {
name: 'Anchor & Hope',
url: 'http://anchorandhopesf.com/'
}
'<a href="{url!escape}">{name!escape}</a>'.format(restaurant)
// => '<a href="http://anchorandhopesf.com/">Anchor & Hope</a>'
$ npm install
$ npm test
FAQs
String formatting inspired by Python's str.format()
The npm package string-format receives a total of 793,978 weekly downloads. As such, string-format popularity was classified as popular.
We found that string-format demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Django has updated its security policies to reject AI-generated vulnerability reports that include fabricated or unverifiable content.
Security News
ECMAScript 2025 introduces Iterator Helpers, Set methods, JSON modules, and more in its latest spec update approved by Ecma in June 2025.
Security News
A new Node.js homepage button linking to paid support for EOL versions has sparked a heated discussion among contributors and the wider community.