What is intl-messageformat?
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.
What are intl-messageformat's main functionalities?
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'
Other packages similar to intl-messageformat
formatjs
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
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
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.
Intl MessageFormat
Format a string with placeholders, including plural and select support to create localized messages.
Overview
Goals
This package aims to provide a way for you to manage and format your JavaScript app's string-based messages into localized string for people using your app. You can use this package in the browser and on the server via Node.js.
This implementation is based on the Strawman Draft. There are a few places this implementation diverges from the strawman draft.
Note: This IntlMessageFormat
API may change to stay in sync with ECMA-402.
How It Works
Messages are provided into the constructor as String
message, or pre-parsed AST.
var msg = new IntlMessageFormat(message, locales, [formats]);
The string message
is parsed, then stored internally in a compiled form that is optimized for generating the formatted string via the format()
method.
var output = msg.format(values);
Common Usage Example
A very common example is formatting messages that have numbers with plural lables. With this package you can make sure that the string is properly formatted for a person's locale, e.g.:
var MESSAGES = {
'en-US': {
NUM_PHOTOS: 'You have {numPhotos, plural, ' +
'=0 {no photos.}' +
'=1 {one photo.}' +
'other {# photos.}}'
},
'es-MX': {
NUM_PHOTOS: 'Usted {numPhotos, plural, ' +
'=0 {no tiene fotos.}' +
'=1 {tiene una foto.}' +
'other {tiene # fotos.}}'
}
};
var output;
var enNumPhotos = new IntlMessageFormat(MESSAGES['en-US'].NUM_PHOTOS, 'en-US');
output = enNumPhotos.format({numPhotos: 1000});
console.log(output);
var esNumPhotos = new IntlMessageFormat(MESSAGES['es-MX'].NUM_PHOTOS, 'es-MX');
output = esNumPhotos.format({numPhotos: 1000});
console.log(output);
Message Syntax
The message syntax that this package uses is not proprietary, in fact it's a common standard message syntax that works across programming languages and one that professional translators are familiar with. This package uses the ICU Message syntax and works for all CLDR languages.
Features
-
Follows ICU Message and CLDR standards.
-
Supports plural and select message arguments.
-
Formats numbers and dates/times in messages using Intl.NumberFormat
and Intl.DateTimeFormat
, respectively.
-
Optimized for repeated calls to an IntlMessageFormat
instance's format()
method.
-
Supports defining custom format styles/options.
-
Supports escape sequences for message syntax chars, e.g.: "\\{foo\\}"
will output: "{foo}"
in the formatted output instead of interpreting it as a foo
argument.
Usage
Intl
Dependency
This package assumes that the Intl
global object exists in the runtime. Intl
is present in all modern browsers except Safari, and there's work happening to integrate Intl
into Node.js.
Luckly, there's the Intl.js polyfill! You will need to conditionally load the polyfill if you want to support runtimes which Intl
is not already built-in.
Public API
IntlMessageFormat
Constructor
To create a message to format, use the IntlMessageFormat constructor. The constructor has three parameters:
-
message - {String | AST} - String message (or pre-parsed AST) that serves as formatting pattern.
-
locales - {String | String[]} - A string with a BCP 47 language tag, or an array of such strings. If you do not provide a locale, the default locale will be used, but you should always provide one!
-
[formats] - {Object} - Optional object with user defined options for format styles.
Creating a Message in Node.js
global.Intl || require('intl');
var IntlMessageFormat = require('intl-messageformat');
var msg = new IntlMessageFormat('My name is {name}.', 'en-US');
Creating a Message in a Browser
<script src="https://cdn.rawgit.com/yahoo/intl-messageformat/v1.0.0-rc-1/dist/intl-messageformat.min.js"></script>
<script>
var msg = new IntlMessageFormat('My name is {name}.', 'en-US');
</script>
format(values)
Method
Once the message is created, formatting the message is done by calling the format()
method on the instance and passing a collection of values
:
var output = msg.format({name: "Eric"});
console.log(output);
Note: A value must be supplied for every argument in the message pattern the instance was constructed with.
User Defined Formats
Define custom format styles is useful you need supply a set of options to the underlying formatter; e.g., outputting a number in USD:
var msg = new IntlMessageFormat('The price is: {price, number, USD}', 'en-US', {
number: {
USD: {
style : 'currency',
currency: 'USD'
}
}
});
var output = msg.format({price: 100});
console.log(output);
In this example, we're defining a USD
number format style which is passed to the underlying Intl.NumberFormat
instance as its options.
License
This software is free to use under the Yahoo! Inc. BSD license.
See the LICENSE file for license text and copyright information.