Unicode MessageFormat for JavaScript
    Preparing search index...

    Class MessageFormat<T, P>

    A message formatter for that implements the LDML 47 MessageFormat specification as well as the TC39 Intl.MessageFormat proposal.

    Type Parameters

    • T extends string = never

      The type used by custom message functions, if any. These extend the default functions.

    • P extends string = T

      The formatted-parts type used by any custom message values.

    Index

    Constructors

    Methods

    Constructors

    Methods

    • Format a message to a string.

      import { MessageFormat } from 'messageformat';
      import { DraftFunctions } from 'messageformat/functions';

      const msg = 'Hello {$user.name}, today is {$date :date style=long}';
      const mf = new MessageFormat('en', msg, { functions: DraftFunctions });
      mf.format({ user: { name: 'Kat' }, date: new Date('2025-03-01') });
      'Hello Kat, today is March 1, 2025'
      

      Parameters

      • OptionalmsgParams: Record<string, unknown>

        Values that may be referenced by $-prefixed variable references. To refer to an inner property of an object value, use . as a separator; in case of conflict, the longest starting substring wins.

      • OptionalonError: (error: unknown) => void

        Called in case of error. If not set, errors are by default logged as warnings.

      Returns string

    • Format a message to a sequence of parts.

      import { MessageFormat } from 'messageformat';
      import { DraftFunctions } from 'messageformat/functions';

      const msg = 'Hello {$user.name}, today is {$date :date style=long}';
      const mf = new MessageFormat('en', msg, { functions: DraftFunctions });
      mf.formatToParts({ user: { name: 'Kat' }, date: new Date('2025-03-01') });
      [
      { type: 'text', value: 'Hello ' },
      { type: 'bidiIsolation', value: '\u2068' },
      { type: 'string', locale: 'en', value: 'Kat' },
      { type: 'bidiIsolation', value: '\u2069' },
      { type: 'text', value: ', today is ' },
      {
      type: 'datetime',
      dir: 'ltr',
      locale: 'en',
      parts: [
      { type: 'month', value: 'March' },
      { type: 'literal', value: ' ' },
      { type: 'day', value: '1' },
      { type: 'literal', value: ', ' },
      { type: 'year', value: '2025' }
      ]
      }
      ]

      Parameters

      • OptionalmsgParams: Record<string, unknown>

        Values that may be referenced by $-prefixed variable references. To refer to an inner property of an object value, use . as a separator; in case of conflict, the longest starting substring wins.

      • OptionalonError: (error: unknown) => void

        Called in case of error. If not set, errors are by default logged as warnings.

      Returns MessagePart<P>[]