message-format
Intl.MessageFormat polyfill supporting ICU message format
Quick Start
npm install message-format --save
adds the library to node_modules
. You can
then use it as follows:
var MessageFormat = require('message-format');
var message = new MessageFormat('Hello { place }!', 'en-US');
var formatted = message.format({ place:'World' });
The library works great with tools like browserify and webpack for use in
front-end code.
Note: message-format relies on Intl.NumberFormat
and Intl.DateTimeFormat
for formatting number
, date
, and time
arguments. If you are in an
environment missing these (like node <= 0.10, IE < 11, or Safari) you'll
need to use a polyfill.
Overview
The ICU Message Format is a great format for user-visible
strings, and includes simple placeholders, number and date placeholders, and
selecting among submessages for gender and plural arguments. The format is
used in apis in C++, PHP, and Java.
message-format is intended as a polyfill for the yet to be standardized
Intl.MessageFormat
api. Since there is only a strawman proposal
at this point, this library represents only one possible way the standard api
could eventually work.
Loading locale data
message-format supports plural rules for all CLDR languages. Locale-aware
formatting of number, date, and time are delegated to the Intl
objects,
and select is the same across all locales. You don't need to load any extra
files for particular locales for message-format.
Supported ICU Formats
number
- percent
, currency
date
- short
, medium
, long
, full
time
- short
, medium
, long
, full
plural
selectordinal
select
Unsupported ICU Formats
ordinal
, duration
, and spellout
arguments are supported by the parser,
but just act like number
. These are not supported by Intl.NumberFormat
.
They require a lot of language-specific code, and would make the library
undesireably large. For now, if you need these kinds of formats, you can pass
them into the message pre-formatted, and refence them in the message pattern
with a simple string placeholder ({ arg }
).
Comparison to intl-messageformat
intl-messageformat is in many ways the inspiration for message-format. However,
intl-messageformat deviates from the ICU standard in the way you escape special
characters in the message pattern, and its pegjs generated parser is fairly
large and not particularly speedy. message-format's primary goals are
simplicity, compliance, and performance (both in size and speed).
If you prefer backslash escaping over the standard quote, you can enable it in
the options:
new MessageFormat('message with \\{braces\\}', 'en-US', { escape:'\\' })
API
MessageFormat
var MessageFormat = require('message-format')
import MessageFormat from 'message-format'
new MessageFormat(pattern, [locales[, options]])
Construct a message format object
Parameters
pattern
is a properly formatted ICU Message Format pattern. A poorly formatted pattern will cause an Error
to be thrown.locales
is an optional string with a BCP 47 language tag, or an array of such strings.options
is an optional object containing options that change the behavior of MessageFormat
.
cache
default true
, if true
cache the result of preparing the format
function. The cache is shared across all instances of MessageFormat
.escape
default '
, if any other character, escape the single character following each escape character.
MessageFormat
instances
message.format([args])
Format the message with the given arguments
Parameters
args
is an object containing the values to replace placeholders with. Required if the pattern contains placeholders.
Examples
Simple string placeholders
var message = new MessageFormat('Welcome back, {name}!');
message.format({ name:'Bob' });
message.format({ name:'Bill' });
Quote escaping rules
Escaping is a little weird in ICU Message Format.
''
is always '
'
begins an escaped string only if followed immediately by a syntax char ({}#
)'
ends an escaped string, unless it is doubled. See #1
The recommendation from ICU is to use the ASCII apostrophe ('
U+0027) only
for escaping syntax characters, and use the pretty single quote (’
U+2019)
for actual apostrophes and single quotes in a message pattern.
var message = new MessageFormat('This isn\'\'t a \'{simple}\' \'string\'');
message.format();
message = new MessageFormat("This isn''t a '{simple}' 'string'");
message.format();
number, date, and time placeholders
var message = new MessageFormat('You took {n,number} pictures since {d,date} {d,time}');
message.format({ n:4000, d:new Date() });
message = new MessageFormat('{ n, number, percent }');
message.format({ n:0.1 });
message = new MessageFormat('{ shorty, date, short }');
message.format({ shorty:new Date() });
selectordinal
var message = new MessageFormat('{ n, selectordinal,\
one {#st}\
two {#nd}\
few {#rd}\
other {#th}\
} place', 'en')
message.format({ n:102 })
Complex string with select and plural in ES6
import MessageFormat from 'message-format'
let message = new MessageFormat(`On { date, date, short } {name} ate {
numBananas, plural,
=0 {no bananas}
=1 {a banana}
other {# bananas}
} {
gender, select,
male {at his house.}
female {at her house.}
other {at their house.}
}`)
message.format({
date: new Date(),
name: 'Curious George',
gender: 'male',
numBananas: 27
})
License
This software is free to use under the MIT license.
See the LICENSE-MIT file for license text and copyright information.