
Security News
npm ‘is’ Package Hijacked in Expanding Supply Chain Attack
The ongoing npm phishing campaign escalates as attackers hijack the popular 'is' package, embedding malware in multiple versions.
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 utility which adds a format
method
to 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 }
.
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:
"{0} x {0} x {0} = {1}".format(3, 3*3*3)
# "3 x 3 x 3 = 27"
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")
# ERROR: 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:
bobby = first_name: "Bobby", last_name: "Fischer"
garry = first_name: "Garry", last_name: "Kasparov"
"{0.first_name} {0.last_name} vs. {1.first_name} {1.last_name}".format(bobby, garry)
# "Bobby Fischer vs. Garry Kasparov"
When referencing the first positional argument, 0.
may be omitted:
repo = owner: "pypy", slug: "pypy", followers: [...]
"{owner}/{slug} has {followers.length} followers".format(repo)
# "pypy/pypy has 516 followers"
If the referenced property is a method, it is invoked and the result is used as the replacement string:
me = name: "David", dob: new Date "26 Apr 1984"
"{name} was born in {dob.getFullYear}".format(me)
# "David was born in 1984"
sheldon = quip: -> "Bazinga!"
"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!"
“Transformers” can be attached to String.prototype.format.transformers
:
String::format.transformers.upper = -> @toUpperCase()
"Batman's preferred onomatopoeia: {0!upper}".format("pow!")
# "Batman's preferred onomatopoeia: POW!"
Within a transformer, this
is the string returned by the referenced object's
toString
method, so transformers may be used in conjunction with non-string
objects:
peter_parker =
first_name: "Peter"
last_name: "Parker"
toString: -> @first_name + " " + @last_name
"NAME: {!upper}".format(peter_parker)
# "NAME: PETER PARKER"
A transformer could sanitizing untrusted input:
String::format.transformers.escape = ->
@replace /[&<>"'`]/g, (chr) -> "&#" + chr.charCodeAt(0) + ";"
"<p class=status>{!escape}</p>".format("I <3 EICH")
# "<p class=status>I <3 EICH</p>"
Or pluralize nouns, perhaps:
String::format.transformers.s = -> "s" unless +this is 1
"{0}, you have {1} unread message{1!s}".format("Holly", 2)
# "Holly, you have 2 unread messages"
"{0}, you have {1} unread message{1!s}".format("Steve", 1)
# "Steve, you have 1 unread message"
String::format does not currently define any transformers.
If a format string is used in multiple places, one could assign it to
a variable to avoid repetition. The idiomatic alternative is to invoke
String::format
with no arguments, which produces a reusable function:
greet = "{0}, you have {1} unread message{1!s}".format()
greet("Holly", 2)
# "Holly, you have 2 unread messages"
greet("Steve", 1)
# "Steve, you have 1 unread message"
make setup
make test
FAQs
String formatting inspired by Python's str.format()
The npm package string-format receives a total of 530,069 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
The ongoing npm phishing campaign escalates as attackers hijack the popular 'is' package, embedding malware in multiple versions.
Security News
A critical flaw in the popular npm form-data package could allow HTTP parameter pollution, affecting millions of projects until patched versions are adopted.
Security News
Bun 1.2.19 introduces isolated installs for smoother monorepo workflows, along with performance boosts, new tooling, and key compatibility fixes.