ICU MessageFormat Parser

2.0.0 · active · verified Tue Apr 21

icu-messageformat-parser is a JavaScript library that provides a PEG.js-based parser for ICU MessageFormat strings. It transforms a given MessageFormat string into an Abstract Syntax Tree (AST), enabling programmatic manipulation or interpretation of localized messages. The current stable version is 4.0.0. New major versions are released periodically to introduce breaking changes, often related to stricter conformance with the ICU MessageFormat specification, and to expand parsing capabilities. Key differentiators include its robust AST output, configurable strictness options (e.g., for number signs and function parameters), and its role as a fundamental parsing component for internationalization workflows involving MessageFormat, prioritizing accurate parsing according to Unicode CLDR and ICU standards.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic parsing, complex selectordinal statements, nested selects, and usage of options for plural key validation and strict mode for '#' parsing.

import { parse } from 'icu-messageformat-parser';

// Basic argument parsing
console.log('Basic argument:', parse('So {wow}.'));
// Expected output: [ 'So ', { type: 'argument', arg: 'wow' }, '.' ]

// Complex selectordinal with octothorpe
const selectOrdinalAst = parse(
  'Such { thing }. { count, selectordinal, one {First} two {Second}' +
  '                  few {Third} other {#th} } word.'
);
console.log('Selectordinal AST:', selectOrdinalAst);

// Nested select statements
const nestedSelectAst = parse(
  'Many{type,select,plural{ numbers}selectordinal{ counting}' +
  'select{ choices}other{ some {type}}}.'
);
console.log('Nested Select AST:', nestedSelectAst);

// Example with options for plural key validation
const msg = '{words, plural, zero{No words} one{One word} other{# words}}';
const englishKeys = { cardinal: [ 'one', 'other' ], ordinal: [ 'one', 'two', 'few', 'other' ] };

console.log('Parsed with default keys (zero is valid):', parse(msg));

try {
  // This will throw an error because 'zero' is not in englishKeys.cardinal
  parse(msg, englishKeys);
} catch (error: any) {
  console.error('Error during parsing with strict keys for plurals:', error.message);
}

// Example demonstrating the `strict` option (replaces `strictNumberSign` in v4+)
// In strict mode, '#' is only special inside plural/selectordinal contexts.
const strictParse = parse('In plural, # is special. Outside, # is text.', { strict: true });
console.log('Strict parsing of #:', strictParse);

view raw JSON →