Security News
The Unpaid Backbone of Open Source: Solo Maintainers Face Increasing Security Demands
Solo open source maintainers face burnout and security challenges, with 60% unpaid and 60% considering quitting.
intl-messageformat
Advanced tools
The intl-messageformat package is a library for internationalization that allows formatting of messages including variable replacement, number and date formatting, and pluralization. It is built on the Internationalization API provided by modern browsers and can be used in both browser and Node.js environments.
Variable Replacement
This feature allows you to insert variables into your message strings.
const IntlMessageFormat = require('intl-messageformat').default;
const message = new IntlMessageFormat('My name is {name}.');
const output = message.format({ name: 'Alice' });
console.log(output); // 'My name is Alice.'
Number Formatting
This feature allows you to format numbers according to the locale, including decimal and thousand separators.
const IntlMessageFormat = require('intl-messageformat').default;
const message = new IntlMessageFormat('The price is {price, number}.', 'en-US');
const output = message.format({ price: 123456.78 });
console.log(output); // 'The price is 123,456.78.'
Date Formatting
This feature allows you to format dates according to the locale.
const IntlMessageFormat = require('intl-messageformat').default;
const message = new IntlMessageFormat('Today is {today, date, long}.', 'en-US');
const output = message.format({ today: new Date() });
console.log(output); // 'Today is January 1, 2020.'
Pluralization
This feature allows you to handle plural forms of words based on numeric values.
const IntlMessageFormat = require('intl-messageformat').default;
const message = new IntlMessageFormat('{numPhotos, plural, =0{no photos} =1{one photo} other{# photos}}', 'en-US');
const output = message.format({ numPhotos: 1000 });
console.log(output); // '1000 photos'
FormatJS is a set of JavaScript libraries that includes intl-messageformat and other internationalization capabilities like message extraction and locale data management. It provides a more comprehensive solution compared to intl-messageformat alone.
i18next is a full-featured internationalization framework for JavaScript. It offers a wide range of features including variable replacement, pluralization, and context handling. It is more feature-rich and has a larger ecosystem compared to intl-messageformat.
Messageformat is a library for ICU MessageFormat strings that supports plural and select messages, nested formats, and more. It is similar to intl-messageformat but also includes a compiler that can optimize message functions.
Format a string with placeholders, including plural and select support to create localized messages.
This IntlMessageFormat
API may change to stay in sync with ECMA-402
To provide a standardized way to concatenate strings with localization support in JavaScript on both the server and client.
This implementation is based on the Strawman Draft. There are a few places this implementation diverges from the strawman draft. One such place is the pattern after it has been parsed. The strawman draft indicates the parsed arguments should be "flat" - where grouping options are at the same level as the type
and valueName
. This, as an example, would look like:
{
type: "plural",
valueName: "TRAVELER_COUNT",
zero: "No travelers",
one: "One traveler",
two: "Two travelers",
few: "There are a few travelers",
many: "There are many travelers",
other: "There are a lot of travelers"
}
This implementation takes a readability approach and places grouping options in an options
key. This looks like:
{
type: "plural",
valueName: "TRAVELER_COUNT",
options: {
zero: "No travelers",
one: "One traveler",
two: "Two travelers",
few: "There are a few travelers",
many: "There are many travelers",
other: "There are a lot of travelers"
}
}
Messages are provided into the constructor as an Array
or String
messages.
var msg = new IntlMessageFormat(pattern, locale, [optFieldFormatters]);
If a String
is provided, it is parsed into a workable Array
of tokens. This means
"Welcome to {CITY}, {STATE}!"
becomes
[
"Welcome to ",
{
valueName: "CITY"
},
", "
{
valueName: "STATE"
},
"!"
]
The pattern Array
may contain Strings
or Objects
. Read more about Token Objects
The pattern is stored internally until the format()
method is called with an Object
containing parameters for generating the message. The pattern is then processed by converting the tokens into strings based on the parameters provided and concatenating the values together.
Custom formatters can be used to format the value after it is gathered from the original process. Custom formatters are stored in the message during construction as the third parameter. Formatters are denoted in the argument with a comma (,) followed by the formatter name.
For example you can ensure that certain tokens are always upper cased:
var msg = new IntlMessageFormat("Then they yelled '{YELL, upper}!'", "en", {
"upper": function (val, locale) {
return val.toString().toUpperCase();
}
});
var m = msg.format({ YELL: "suprise" });
// Then they yelled 'SUPRISE!'
Install using npm:
$ npm install intl-messageformat
To create a message to format, use the IntlMessageFormat constructor. The constructor has three parameters:
pattern - {String|Array} - Array or string that serves as formatting pattern. Use array for plural and select messages, otherwise use string form.
locale - {String} - Locale for string formatting. The locale is optional, but it is highly encouraged to provide a locale. If you do not provide a locale, the default locale will be used.
optFieldFormatters - {Object} - (optional) Holds user defined formatters for each field
var IntlMessageFormat = require('intl-messageformat');
// load some locales that you care about
require('intl-messageformat/locale-data/en');
require('intl-messageformat/locale-data/ar');
require('intl-messageformat/locale-data/pl');
var msg = new IntlMessageFormat("My name is {NAME}.", "en-US");
var msg = new IntlMessageFormat("My name is {NAME}.", "en-US");
Once the message is created, formatting the message is done by calling the format
method of the instantiated object:
var myNameIs = msg.format({ NAME: "Ferris Wheeler"});
// "My name is Ferris Wheeler."
Token objects are created when the string is parsed. If you wish, you can create your own token objects. Token objects should always at least contain a valueName
. There are a few other items that can be included:
type
{String} - plural
or select
to identify the grouping type. Other values such as number
and date
are used to identify the type of the value and can be combined with a format
string to identify a formatter to be used.
valueName
{String} - key to match the format
object
format
{String|Function} - formatter used on the value after is discovered. Specifying the type
is "number"
and the format
is "integer"
would result in the default formatter number_integer
being called
options
{Object} - each key should be matched based on the type
specified
zero
{String|Array} - (plural) Matched when the locale determines that the number is in the "zero"
pluralization class
one
{String|Array} - (plural) Matched when the locale determines that the number is in the "one"
pluralization class
two
{String|Array} - (plural) Matched when the locale determines that the number is in the "two"
pluralization class
few
{String|Array} - (plural) Matched when the locale determines that the number is in the "few"
pluralization class
many
{String|Array} - (plural) Matched when the locale determines that the number is in the "many"
pluralization class
male
{String|Array} - (select) Matched when the valueName
returns "male"
female
{String|Array} - (select) Matched when the valueName
returns "female"
neuter
{String|Array} - (select) Matched when the valueName
returns "neuter"
other
{String|Array} - (plural or select) Matched when _normalizeCount
returns "other"
, the valueName
returns "other"
or the returned value from either of those returns a value that is not specified. For instance, if "male"
is returned and "male"
is not specified, other will be matched.
When options
is matched and returns an Array
, that Array
is then processed in the same manner. This means, large complex, conditional messages can be formed by defining the pattern as such.
This package ships with locale data for the top-level locales (e.g. en
but not en-US
). You can load the library and locale(s) using any of the following subpaths in the package:
Load the base and then just the locale(s) that you need: intl-messageformat/index.js
and intl-messageformat/locale-data/{locale}.js
.
Load the base with a single locale builtin: intl-messageformat/build/intl-messageformat.{locale}.js')
. You can then optionally add more locale(s) as above.
Load all locales: intl-messageformat/build/intl-messageformat.complete.js
.
Please note that if you are loading from the locale-data/
directory that those files are expecting the library to be available in the IntlMessageFormat
variable.
Every intl-messageformat/build/*.js
file also has an intl-messageformat/build/*.min.js
equivalent which has already been minified.
var msg = new IntlMessageFormat("My name is {name}.", "en-US");
var myNameIs = msg.format({ name: "Ferris Wheeler"});
// "My name is Ferris Wheeler."
var msg = new IntlMessageFormat(['Some text before ', {
type: 'plural',
valueName: 'NUM_PEOPLE',
offset: 1,
options: {
one: 'Some message ${PH} with ${#} value',
few: ['Optional prefix text for |few| ', {
type: 'select',
valueName: 'GENDER',
options: {
male: 'Text for male option with \' single quotes',
female: 'Text for female option with {}',
other: 'Text for default'
}
}, ' optional postfix text'],
other: 'Some messages for the default'
}
}, ' and text after'], "en-US");
var complex = msg.format({
NUM_PEOPLE: 4,
PH: 'whatever',
GENDER: 'male'
});
// "Some text before Optional prefix text for |few| Text for male option with ' single quotes optional postfix text and text after"
User defined formatters are provided to the IntlMessageFormat as the third parameter. To denote a key should be process through a formatter, you need only provide the formatter name after the token key. Such as, {key}
would then become {key, formatter}
. This is an example of using the Intl.NumberFormat to create a currency formatter.
var msg = new IntlMessageFormatter("I just made {TOTAL, currency}!!", "en-US", {
currency: function (val, locale) {
return new Intl.NumberFormat(val, {
style: 'currency',
currency: 'USD',
currencyDisplay: 'symbol'
});
}
});
var payday = msg.format({ TOTAL: 3 });
// I just made $3.00!!
Creates IntlMessageFormat object from a pattern, locale and field formatters. String patterns are broken down to Arrays. Objects should match the following pattern:
{
type: 'plural|select',
valueName: 'string',
offset: 1, // consistent offsets for plurals
options: {}, // keys match options for plurals and selects
format: 'string|function' // strings are matched to internal formatters
}
Parameters
pattern
: {Array|String} Array
or String
that serves as formatting
pattern. An Array
may consist of Strings
and Token Objects.
locale
: {String} Locale for string formatting and when using plurals and formatters.
optFieldFormatters
: {Object} Holds user defined formatters for each
field
Formats the pattern with supplied parameters. Dates, times and numbers are formatted in locale sensitive way when used with a formatter.
PARAMETERS
data
: {Object} Object used to choose options when formatting the messageNOT YET DETERMINED Returns resolved options, in this case supported locale.
This software is free to use under the Yahoo! Inc. BSD license. See the LICENSE file for license text and copyright information.
FAQs
Formats ICU Message strings with number, date, plural, and select placeholders to create localized messages.
The npm package intl-messageformat receives a total of 3,643,687 weekly downloads. As such, intl-messageformat popularity was classified as popular.
We found that intl-messageformat demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 12 open source maintainers 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
Solo open source maintainers face burnout and security challenges, with 60% unpaid and 60% considering quitting.
Security News
License exceptions modify the terms of open source licenses, impacting how software can be used, modified, and distributed. Developers should be aware of the legal implications of these exceptions.
Security News
A developer is accusing Tencent of violating the GPL by modifying a Python utility and changing its license to BSD, highlighting the importance of copyleft compliance.