new MessageFormat(localeopt)
Create a new message formatter
If locale
is not set, calls to compile()
will fetch the default locale
each time. A string locale
will create a single-locale MessageFormat
instance, with pluralisation rules fetched from the Unicode CLDR using
make-plural.
Using an array of strings as locale
will create a MessageFormat object
with multi-language support, with pluralisation rules fetched as above. To
select which to use, use the second parameter of compile()
, or use message
keys corresponding to your locales.
Using an object locale
with all properties of type function
allows for
the use of custom/externally defined pluralisation rules.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
locale |
string | Array.<string> | Object.<string, function()> |
<optional> |
The locale(s) to use |
Namespaces
Members
(static) defaultLocale
The default locale
Read by compile()
when no locale has been previously set
Methods
(static) escape(str) → {string}
Escape special characaters
Prefix the characters #
, {
, }
and \
in the input string with a \
.
This will allow those characters to not be considered as MessageFormat
control characters.
Parameters:
Name | Type | Description |
---|---|---|
str |
string | The input string |
Returns:
The escaped string
- Type
- string
addFormatters(fmt) → {MessageFormat}
Add custom formatter functions to this MessageFormat instance
The general syntax for calling a formatting function in MessageFormat is
{var, fn[, args]*}
, where var
is the variable that will be set by the
user code, fn
determines the formatting function, and args
is an
optional comma-separated list of additional arguments.
In JavaScript, each formatting function is called with three parameters;
the variable value v
, the current locale lc
, and (if set) args
as a
single string, or an array of strings. Formatting functions should not have
side effects.
Parameters:
Name | Type | Description |
---|---|---|
fmt |
Object.<string, function()> | A map of formatting functions |
- Source:
- See:
Returns:
The MessageFormat instance, to allow for chaining
- Type
- MessageFormat
Example
var mf = new MessageFormat('en-GB');
mf.addFormatters({
upcase: function(v) { return v.toUpperCase(); },
locale: function(v, lc) { return lc; },
prop: function(v, lc, p) { return v[p] }
});
mf.compile('This is {VAR, upcase}.')({ VAR: 'big' })
// 'This is BIG.'
mf.compile('The current locale is {_, locale}.')({ _: '' })
// 'The current locale is en-GB.'
mf.compile('Answer: {obj, prop, a}')({ obj: {q: 3, a: 42} })
// 'Answer: 42'
compile(messages, localeopt) → {function|Object}
Compile messages into storable functions
If messages
is a single string including ICU MessageFormat declarations,
the result of compile()
is a function taking a single Object parameter
d
representing each of the input's defined variables.
If messages
is a hierarchical structure of such strings, the output of
compile()
will match that structure, with each string replaced by its
corresponding JavaScript function.
If the input messages
-- and therefore the output -- of compile()
is an
object, the output object will have a toString(global)
method that may be
used to store or cache the compiled functions to disk, for later inclusion
in any JS environment, without a local MessageFormat instance required. Its
global
parameters sets the name (if any) of the resulting global variable,
with special handling for exports
, module.exports
, and export default
.
If global
does not contain a .
, the output defaults to an UMD pattern.
If locale
is not set, the first locale set in the object's constructor
will be used by default; using a key at any depth of messages
that is a
declared locale will set its child elements to use that locale.
If locale
is set, it is used for all messages. If the constructor
declared any locales, locale
needs to be one of them.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
messages |
string | Object | The input message(s) to be compiled, in ICU MessageFormat |
|
locale |
string |
<optional> |
A locale to use for the messages |
Returns:
The first match found for the given locale(s)
- Type
- function | Object
Examples
var mf = new MessageFormat('en');
var cf = mf.compile('A {TYPE} example.');
cf({ TYPE: 'simple' })
// 'A simple example.'
var mf = new MessageFormat(['en', 'fi']);
var cf = mf.compile({
en: { a: 'A {TYPE} example.',
b: 'This is the {COUNT, selectordinal, one{#st} two{#nd} few{#rd} other{#th}} example.' },
fi: { a: '{TYPE} esimerkki.',
b: 'Tämä on {COUNT, selectordinal, other{#.}} esimerkki.' }
});
cf.en.b({ COUNT: 2 })
// 'This is the 2nd example.'
cf.fi.b({ COUNT: 2 })
// 'Tämä on 2. esimerkki.'
var fs = require('fs');
var mf = new MessageFormat('en');
var msgSet = {
a: 'A {TYPE} example.',
b: 'This has {COUNT, plural, one{one member} other{# members}}.',
c: 'We have {P, number, percent} code coverage.'
};
var cfStr = mf.compile(msgSet).toString('module.exports');
fs.writeFileSync('messages.js', cfStr);
...
var messages = require('./messages');
messages.a({ TYPE: 'more complex' })
// 'A more complex example.'
messages.b({ COUNT: 3 })
// 'This has 3 members.'
disablePluralKeyChecks() → {MessageFormat}
Disable the validation of plural & selectordinal keys
Previous versions of messageformat.js allowed the use of plural & selectordinal statements with any keys; now we throw an error when a statement uses a non-numerical key that will never be matched as a pluralization category for the current locale.
Use this method to disable the validation and allow usage as previously. To re-enable, you'll need to create a new MessageFormat instance.
Returns:
The MessageFormat instance, to allow for chaining
- Type
- MessageFormat
Example
var mf = new MessageFormat('en');
var msg = '{X, plural, zero{no answers} one{an answer} other{# answers}}';
mf.compile(msg);
// Error: Invalid key `zero` for argument `X`. Valid plural keys for this
// locale are `one`, `other`, and explicit keys like `=0`.
mf.disablePluralKeyChecks();
mf.compile(msg)({ X: 0 });
// '0 answers'
setBiDiSupport(enableopt) → {MessageFormat}
Enable or disable the addition of Unicode control characters to all input to preserve the integrity of the output when mixing LTR and RTL text.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
enable |
boolean |
<optional> |
true |
- Source:
- See:
Returns:
The MessageFormat instance, to allow for chaining
- Type
- MessageFormat
Example
// upper case stands for RTL characters, output is shown as rendered
var mf = new MessageFormat('en');
mf.compile('{0} >> {1} >> {2}')(['first', 'SECOND', 'THIRD']);
// 'first >> THIRD << SECOND'
mf.setBiDiSupport(true);
mf.compile('{0} >> {1} >> {2}')(['first', 'SECOND', 'THIRD']);
// 'first >> SECOND >> THIRD'
setStrictNumberSign(enableopt) → {MessageFormat}
According to the ICU MessageFormat spec, a #
character directly inside a
plural
or selectordinal
statement should be replaced by the number
matching the surrounding statement. By default, messageformat.js will
replace #
signs with the value of the nearest surrounding plural
or
selectordinal
statement.
Set this to true to follow the stricter ICU MessageFormat spec, and to
throw a runtime error if #
is used with non-numeric input.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
enable |
boolean |
<optional> |
true |
Returns:
The MessageFormat instance, to allow for chaining
- Type
- MessageFormat
Example
var mf = new MessageFormat('en');
var cookieMsg = '#: {X, plural, =0{no cookies} one{a cookie} other{# cookies}}';
mf.compile(cookieMsg)({ X: 3 });
// '#: 3 cookies'
var pastryMsg = '{X, plural, one{{P, select, cookie{a cookie} other{a pie}}} other{{P, select, cookie{# cookies} other{# pies}}}}';
mf.compile(pastryMsg)({ X: 3, P: 'pie' });
// '3 pies'
mf.setStrictNumberSign(true);
mf.compile(pastryMsg)({ X: 3, P: 'pie' });
// '# pies'