Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

message-format

format-message17.5kMIT6.2.4TypeScript support: included

Intl.MessageFormat prollyfill supporting ICU message format

i18n, intl, internationalization, localization, globalization, messageformat, pluralformat, selectformat, parser, plural, gender, icu

readme

message-format

Intl.MessageFormat prollyfill supporting ICU message format

npm Version JS Standard Style

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('en-US', 'Hello { place }!');
var formatted = message.format({ place:'World' });

The library works great with tools like browserify and webpack for use in front-end code. Also check out format-message for an alternative API and inlining translations at build time.

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.12, IE < 11, or Safari < 10) you'll need to use a polyfill. If Intl formats are missing, an error occurs when formatting these arguments.

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, hence "prollyfill".

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 }).

API

MessageFormat

var MessageFormat = require('message-format')
// or
import MessageFormat from 'message-format'

new MessageFormat(locales, pattern)

Construct a message format object

Parameters

  • locales is a string with a BCP 47 language tag, or an array of such strings.
  • pattern is a properly formatted ICU Message Format pattern. A poorly formatted pattern will cause an Error to be thrown.

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('en', 'Welcome back, {name}!');
message.format({ name:'Bob' }); // "Welcome back, Bob!"
message.format({ name:'Bill' }); // "Welcome back, Bill!"

Quote escaping rules

Escaping is a little weird in ICU Message Format.

  1. '' is always '
  2. ' begins an escaped string only if followed immediately by a syntax char ({}#)
  3. ' 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('en', 'This isn\'\'t a \'{simple}\' \'string\'');
message.format(); // "This isn't a {simple} 'string'"

// double quotes or backticks (ES6) make it a little easier to read
message = new MessageFormat("en", "This isn''t a '{simple}' 'string'");
message.format(); // "This isn't a {simple} 'string'"

number, date, and time placeholders

var message = new MessageFormat('en', 'You took {n,number} pictures since {d,date} {d,time}');
message.format({ n:4000, d:new Date() }); // "You took 4,000 pictures since Jan 1, 2015 9:33:04 AM"

message = new MessageFormat('en', '{ n, number, percent }');
message.format({ n:0.1 }); // "10%"

message = new MessageFormat('en', '{ shorty, date, short }');
message.format({ shorty:new Date() }); // "1/1/15"

selectordinal

var message = new MessageFormat('en', '{ n, selectordinal,\
  one {#st}\
  two {#nd}\
  few {#rd}\
  other {#th}\
} place')
message.format({ n:102 }) // "102nd place"

Complex string with select and plural in ES6

import MessageFormat from 'message-format'

// using a template string for multiline, no interpolation
let message = new MessageFormat('en', `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
}) // "On 1/1/15 Curious George ate 27 bananas at his house."

License

This software is free to use under the MIT license. See the LICENSE-MIT file for license text and copyright information.

changelog

Changelog

6.2.4

Update the TypeScript type definition for MessageFormat.supportedLocalesOf() to communicate that it is a static method.

6.2.0

Add TypeScript type definitions.

6.0.3

Use var declarations for wider compatibility.

6.0.0

Breaking Change Calling MessageFormat without new throws an error, to better match newer constructors added to JavaScript and Intl.

The order of arguments passed to MessageFormat have changed.

Updated supportedLocalesOf to be the union of supportedLocalesOf functions on Intl.NumberFormat, Intl.DateTimeFormat, and Intl.PluralRules.

New Feature Custom placeholder types can be supported by passing in a new argument with formatter functions.

5.2.1

Updated CLDR plural rules.

5.0.0

This only updated the dependencies and bumped the version to match related libraries.

  • Breaking Change
    • The fallback for missing Intl was removed from format-message-interpret.

2.0.0

  • Spec Compliancy
    • supportedLocalesOf now matches the behavior of Intl.* apis
    • format is defined as a getter for a function, just like other Intl.* apis
    • Update to CLDR 28
    • Removed escape option allowing for backslash escaping
  • Breaking Change
    • Can no longer get the full list of supported locales via supportedLocalesOf
    • Parameter order has been reversed, so locales is first, just like Intl.* apis
    • Removed cache option
    • Removed parser and printer apis, refer instead to format-message-parse and format-message-print

1.2.1

  • Internal
    • Update metadata for new github org
    • Update dependencies

1.2.0

  • Spec Compliancy
    • Update to CLDR 27 (adds 'as' and 'ce' locales)

1.1.0

  • Bug Fix
    • Fallback to toLocaleString methods when Intl is unavailable
  • Polish
    • Better test error conditions
  • Internal
  • Documentation
    • Document fallback behavior
    • Include a plug for format-message

1.0.0

  • Polish
    • Provide index.js for platforms that don't read package.json for main.
    • Provide message-format/parser for access to parser.
    • Provide message-format/printer for access to printer.
  • Documentation
    • Document parser and printer high-level api.
  • Internal
    • Refactor error handling in parser.
    • Use lib folder instead of dist for built files.

0.1.0

  • New Feature
    • Added support for selectordinal.
    • Added pretty printer module message-format/dist/printer.
    • Added browser minified version with global Intl.MessageFormat at dist/browser.js.
  • Bug Fix
    • Fix bad caching in interpreter.
    • Format unsupported rbnf types as number.
  • Internal
    • Upgrade from 6to5 to babel.
    • Use eslint and jscs for style checking.