i18n-js v4.5.2
    Preparing search index...

    Class I18n

    Index

    Constructors

    Properties

    defaultSeparator: string

    Set the default string separator. Defaults to ., as in scope.translation.

    distanceOfTimeInWords: (
        fromTime: DateTime,
        toTime: DateTime,
        options?: TimeAgoInWordsOptions,
    ) => string = ...

    Alias for timeAgoInWords.

    Type declaration

      • (fromTime: DateTime, toTime: DateTime, options?: TimeAgoInWordsOptions): string
      • Reports the approximate distance in time between two time representations.

        Parameters

        Returns string

        The distance in time representation.

    enableFallback: boolean

    Set if engine should fallback to the default locale when a translation is missing. Defaults to false.

    When enabled, missing translations will first be looked for in less specific versions of the requested locale and if that fails by taking them from your I18n#defaultLocale.

    interpolate: Object

    Override the interpolation function. For the default implementation, see https://github.com/fnando/i18n/tree/main/src/helpers/interpolate.ts

    l: (
        type: string,
        value: undefined | null | string | number | Date,
        options?: Dict,
    ) => string = ...

    Alias for localize.

    Type declaration

      • (
            type: string,
            value: undefined | null | string | number | Date,
            options?: Dict,
        ): string
      • Localize several values.

        You can provide the following scopes: currency, number, or percentage. If you provide a scope that matches the /^(date|time)/ regular expression then the value will be converted by using the I18n.toTime function. It will default to the value's toString function.

        If value is either null or undefined then an empty string will be returned, regardless of what localization type has been used.

        Parameters

        • type: string

          The localization type.

        • value: undefined | null | string | number | Date

          The value that must be localized.

        • Optionaloptions: Dict

          The localization options.

        Returns string

        The localized string.

    locales: Locales

    The locale resolver registry.

    Locales

    missingBehavior: string

    Set missing translation behavior.

    • message will display a message that the translation is missing.
    • guess will try to guess the string.
    • error will raise an exception whenever a translation is not defined.

    See MissingTranslation.register for instructions on how to define your own behavior.

    missingPlaceholder: MissingPlaceholderHandler

    Return a missing placeholder message for given parameters.

    missingTranslation: MissingTranslation

    The missing translation behavior registry.

    missingTranslationPrefix: string

    If you use missingBehavior with 'message', but want to know that the string is actually missing for testing purposes, you can prefix the guessed string by setting the value here. By default, no prefix is used.

    nullPlaceholder: NullPlaceholderHandler

    Return a placeholder message for null values. Defaults to the same behavior as I18n.missingPlaceholder.

    onChangeHandlers: OnChangeHandler[] = []

    List of all onChange handlers.

    p: (count: number, scope: Scope, options?: TranslateOptions) => string = ...

    Alias for pluralize.

    Type declaration

      • (count: number, scope: Scope, options?: TranslateOptions): string
      • Pluralize the given scope using the count value. The pluralized translation may have other placeholders, which will be retrieved from options.

        Parameters

        • count: number

          The counting number.

        • scope: Scope

          The translation scope.

        • Optionaloptions: TranslateOptions

          The translation options.

        Returns string

        The translated string.

    placeholder: RegExp

    Set the placeholder format. Accepts {{placeholder}} and %{placeholder}.

    pluralization: Pluralization

    The pluralization behavior registry.

    t: <T = string>(scope: Scope, options?: TranslateOptions) => string | T = ...

    Alias for translate.

    Type declaration

      • <T = string>(scope: Scope, options?: TranslateOptions): string | T
      • Translate the given scope with the provided options.

        Type Parameters

        • T = string

        Parameters

        • scope: Scope

          The scope that will be used.

        • Optionaloptions: TranslateOptions

          The options that will be used on the translation. Can include some special options like defaultValue, count, and scope. Everything else will be treated as replacement values.

          • [key: string]: any
          • Optionalcount?: number
          • Optionaldefaults?: Dict[]
          • OptionaldefaultValue?: any
          • OptionalmissingBehavior?: string
          • Optionalscope?: Scope

        Returns string | T

        The translated string.

    transformKey: (key: string) => string

    Transform keys. By default, it returns the key as it is, but allows for overriding. For instance, you can set a function to receive the camelcase key, and convert it to snake case.

    translations: Dict = {}

    Set the registered translations. The root key must always be the locale (and its variations with region).

    Remember that no events will be triggered if you change this object directly. To trigger onchange events, you must perform updates either using I18n#store or I18n#update.

    Accessors

    • get defaultLocale(): string

      Return the default locale, using a explicit locale set using i18n.defaultLocale = locale, the default locale set using i18n.defaultLocale or the fallback, which is en.

      Returns string

      The current locale.

    • set defaultLocale(newLocale: string): void

      Set the default locale explicitly.

      Parameters

      • newLocale: string

        The new locale.

      Returns void

    • get locale(): string

      Return the current locale, using a explicit locale set using i18n.locale = newLocale, the default locale set using i18n.defaultLocale or the fallback, which is en.

      Returns string

      The current locale.

    • set locale(newLocale: string): void

      Set the current locale explicitly.

      Parameters

      • newLocale: string

        The new locale.

      Returns void

    • get version(): number

      Return the change version. This value is incremented whenever I18n#store or I18n#update is called, or when I18n#locale/I18n#defaultLocale is set.

      Returns number

    Methods

    • Formats a number.

      Parameters

      • input: Numeric

        The numeric value that will be formatted.

      • options: Partial<FormatNumberOptions> = {}

        The formatting options. Defaults to: { delimiter: ",", precision: 3, separator: ".", unit: "", format: "%u%n", significant: false, stripInsignificantZeros: false, }

      Returns string

      The formatted number.

    • Parameters

      • scope: Scope

        The scope lookup path.

      Returns any

      The found scope.

    • Localize several values.

      You can provide the following scopes: currency, number, or percentage. If you provide a scope that matches the /^(date|time)/ regular expression then the value will be converted by using the I18n.toTime function. It will default to the value's toString function.

      If value is either null or undefined then an empty string will be returned, regardless of what localization type has been used.

      Parameters

      • type: string

        The localization type.

      • value: undefined | null | string | number | Date

        The value that must be localized.

      • Optionaloptions: Dict

        The localization options.

      Returns string

      The localized string.

    • Formats a number into a currency string (e.g., $13.65). You can customize the format in the using an options object.

      The currency unit and number formatting of the current locale will be used unless otherwise specified in the provided options. No currency conversion is performed. If the user is given a way to change their locale, they will also be able to change the relative value of the currency displayed with this helper.

      Parameters

      • input: Numeric

        The number to be formatted.

      • options: Partial<FormatNumberOptions> = {}

        The formatting options. When defined, supersedes the default options defined by number.format and number.currency.*.

        • precision

          Sets the level of precision (defaults to 2).

        • roundMode

          Determine how rounding is performed (defaults to default.)

        • unit

          Sets the denomination of the currency (defaults to "$").

        • separator

          Sets the separator between the units (defaults to ".").

        • delimiter

          Sets the thousands delimiter (defaults to ",").

        • format

          Sets the format for non-negative numbers (defaults to "%u%n"). Fields are %u for the currency, and %n for the number.

        • negativeFormat

          Sets the format for negative numbers (defaults to prepending a hyphen to the formatted number given by format). Accepts the same fields than format, except %n is here the absolute value of the number.

        • stripInsignificantZeros

          If true removes insignificant zeros after the decimal separator (defaults to false).

        • raise

          If true, raises exception for non-numeric values like NaN and infinite values.

      Returns string

      The formatted number.

      i18n.numberToCurrency(1234567890.5);
      // => "$1,234,567,890.50"

      i18n.numberToCurrency(1234567890.506);
      // => "$1,234,567,890.51"

      i18n.numberToCurrency(1234567890.506, { precision: 3 });
      // => "$1,234,567,890.506"

      i18n.numberToCurrency("123a456");
      // => "$123a456"

      i18n.numberToCurrency("123a456", { raise: true });
      // => raises exception ("123a456" is not a valid numeric value)

      i18n.numberToCurrency(-0.456789, { precision: 0 });
      // => "$0"

      i18n.numberToCurrency(-1234567890.5, { negativeFormat: "(%u%n)" });
      // => "($1,234,567,890.50)"

      i18n.numberToCurrency(1234567890.5, {
      unit: "&pound;",
      separator: ",",
      delimiter: "",
      });
      // => "&pound;1234567890,50"

      i18n.numberToCurrency(1234567890.5, {
      unit: "&pound;",
      separator: ",",
      delimiter: "",
      format: "%n %u",
      });
      // => "1234567890,50 &pound;"

      i18n.numberToCurrency(1234567890.5, { stripInsignificantZeros: true });
      // => "$1,234,567,890.5"

      i18n.numberToCurrency(1234567890.5, { precision: 0, roundMode: "up" });
      // => "$1,234,567,891"
    • Formats a +number+ with grouped thousands using delimiter (e.g., 12,324). You can customize the format in the options parameter.

      Parameters

      • input: Numeric

        The numeric value that will be formatted.

      • options: Partial<NumberToDelimitedOptions> = {}

        The formatting options.

        • delimiter

          Sets the thousands delimiter (defaults to ",").

        • separator

          Sets the separator between the fractional and integer digits (defaults to ".").

        • delimiterPattern

          Sets a custom regular expression used for deriving the placement of delimiter. Helpful when using currency formats like INR.

      Returns string

      The formatted number.

      i18n.numberToDelimited(12345678);
      // => "12,345,678"

      i18n.numberToDelimited("123456");
      // => "123,456"

      i18n.numberToDelimited(12345678.05);
      // => "12,345,678.05"

      i18n.numberToDelimited(12345678, { delimiter: "." });
      // => "12.345.678"

      i18n.numberToDelimited(12345678, { delimiter: "," });
      // => "12,345,678"

      i18n.numberToDelimited(12345678.05, { separator: " " });
      // => "12,345,678 05"

      i18n.numberToDelimited("112a");
      // => "112a"

      i18n.numberToDelimited(98765432.98, { delimiter: " ", separator: "," });
      // => "98 765 432,98"

      i18n.numberToDelimited("123456.78", {
      delimiterPattern: /(\d+?)(?=(\d\d)+(\d)(?!\d))/g,
      });
      // => "1,23,456.78"
    • Convert a number into a readable representation.

      Parameters

      • input: Numeric

        The number that will be formatted.

      • options: Partial<NumberToHumanOptions> = {}

        The formatting options. When defined, supersedes the default options stored at number.human.format.* and number.human.storage_units.*.

        • precision

          Sets the precision of the number (defaults to 3).

        • roundMode

          Determine how rounding is performed (defaults to default).

        • significant

          If true, precision will be the number of significant_digits. If false, the number of fractional digits (defaults to true)

        • separator

          Sets the separator between the fractional and integer digits (defaults to ".").

        • delimiter

          Sets the thousands delimiter (defaults to "").

        • stripInsignificantZeros

          If true removes insignificant zeros after the decimal separator (defaults to true).

        • units

          A Hash of unit quantifier names. Or a string containing an I18n scope where to find this object. It might have the following keys:

          • integers: unit, ten, hundred, thousand, million, billion, trillion, quadrillion
          • fractionals: deci, centi, mili, micro, nano, pico, femto
        • format

          Sets the format of the output string (defaults to "%n %u"). The field types are:

          • %u - The quantifier (ex.: 'thousand')
          • %n - The number

      Returns string

      The formatted number.

      i18n.numberToHuman(123);
      // => "123"

      i18n.numberToHuman(1234);
      // => "1.23 Thousand"

      i18n.numberToHuman(12345);
      // => "12.3 Thousand"

      i18n.numberToHuman(1234567);
      // => "1.23 Million"

      i18n.numberToHuman(1234567890);
      // => "1.23 Billion"

      i18n.numberToHuman(1234567890123);
      // => "1.23 Trillion"

      i18n.numberToHuman(1234567890123456);
      // => "1.23 Quadrillion"

      i18n.numberToHuman(1234567890123456789);
      // => "1230 Quadrillion"

      i18n.numberToHuman(489939, { precision: 2 });
      // => "490 Thousand"

      i18n.numberToHuman(489939, { precision: 4 });
      // => "489.9 Thousand"

      i18n.numberToHuman(489939, { precision: 2, roundMode: "down" });
      // => "480 Thousand"

      i18n.numberToHuman(1234567, { precision: 4, significant: false });
      // => "1.2346 Million"

      i18n.numberToHuman(1234567, {
      precision: 1,
      separator: ",",
      significant: false,
      });
      // => "1,2 Million"

      i18n.numberToHuman(500000000, { precision: 5 });
      // => "500 Million"

      i18n.numberToHuman(12345012345, { significant: false });
      // => "12.345 Billion"

      Non-significant zeros after the decimal separator are stripped out by default (set stripInsignificantZeros to false to change that):

      i18n.numberToHuman(12.00001);
      // => "12"

      i18n.numberToHuman(12.00001, { stripInsignificantZeros: false });
      // => "12.0"

      You can also use your own custom unit quantifiers:

      i18n.numberToHuman(500000, units: { unit: "ml", thousand: "lt" });
      // => "500 lt"

      If in your I18n locale you have:

      ---
      en:
      distance:
      centi:
      one: "centimeter"
      other: "centimeters"
      unit:
      one: "meter"
      other: "meters"
      thousand:
      one: "kilometer"
      other: "kilometers"
      billion: "gazillion-distance"

      Then you could do:

      i18n.numberToHuman(543934, { units: "distance" });
      // => "544 kilometers"

      i18n.numberToHuman(54393498, { units: "distance" });
      // => "54400 kilometers"

      i18n.numberToHuman(54393498000, { units: "distance" });
      // => "54.4 gazillion-distance"

      i18n.numberToHuman(343, { units: "distance", precision: 1 });
      // => "300 meters"

      i18n.numberToHuman(1, { units: "distance" });
      // => "1 meter"

      i18n.numberToHuman(0.34, { units: "distance" });
      // => "34 centimeters"
    • Convert a number into a readable size representation.

      Parameters

      • input: Numeric

        The number that will be formatted.

      • options: Partial<NumberToHumanSizeOptions> = {}

        The formatting options. When defined, supersedes the default options stored at number.human.storage_units.* and number.human.format.

        • precision

          Sets the precision of the number (defaults to 3).

        • roundMode

          Determine how rounding is performed (defaults to default)

        • significant

          If true, precision will be the number of significant digits. If false, the number of fractional digits (defaults to true).

        • separator

          Sets the separator between the fractional and integer digits (defaults to ".").

        • delimiter

          Sets the thousands delimiter (defaults to "").

        • stripInsignificantZeros

          If true removes insignificant zeros after the decimal separator (defaults to true).

      Returns string

      The formatted number.

      i18n.numberToHumanSize(123)
      // => "123 Bytes"

      i18n.numberToHumanSize(1234)
      // => "1.21 KB"

      i18n.numberToHumanSize(12345)
      // => "12.1 KB"

      i18n.numberToHumanSize(1234567)
      // => "1.18 MB"

      i18n.numberToHumanSize(1234567890)
      // => "1.15 GB"

      i18n.numberToHumanSize(1234567890123)
      // => "1.12 TB"

      i18n.numberToHumanSize(1234567890123456)
      // => "1.1 PB"

      i18n.numberToHumanSize(1234567890123456789)
      // => "1.07 EB"

      i18n.numberToHumanSize(1234567, {precision: 2})
      // => "1.2 MB"

      i18n.numberToHumanSize(483989, precision: 2)
      // => "470 KB"

      i18n.numberToHumanSize(483989, {precision: 2, roundMode: "up"})
      // => "480 KB"

      i18n.numberToHumanSize(1234567, {precision: 2, separator: ","})
      // => "1,2 MB"

      i18n.numberToHumanSize(1234567890123, {precision: 5})
      // => "1.1228 TB"

      i18n.numberToHumanSize(524288000, {precision: 5})
      // => "500 MB"
    • Convert a number into a formatted percentage value.

      Parameters

      • input: Numeric

        The number to be formatted.

      • options: Partial<NumberToPercentageOptions> = {}

        The formatting options. When defined, supersedes the default options stored at number.format and number.percentage.*.

        • precision

          Sets the level of precision (defaults to 3).

        • roundMode

          Determine how rounding is performed (defaults to default.)

        • separator

          Sets the separator between the units (defaults to ".").

        • delimiter

          Sets the thousands delimiter (defaults to "").

        • format

          Sets the format for non-negative numbers (defaults to "%n%"). The number field is represented by %n.

        • negativeFormat

          Sets the format for negative numbers (defaults to prepending a hyphen to the formatted number given by format). Accepts the same fields than format, except %n is here the absolute value of the number.

        • stripInsignificantZeros

          If true removes insignificant zeros after the decimal separator (defaults to false).

      Returns string

      The formatted number.

      i18n.numberToPercentage(100);
      // => "100.000%"

      i18n.numberToPercentage("98");
      // => "98.000%"

      i18n.numberToPercentage(100, { precision: 0 });
      // => "100%"

      i18n.numberToPercentage(1000, { delimiter: ".", separator: "," });
      // => "1.000,000%"

      i18n.numberToPercentage(302.24398923423, { precision: 5 });
      // => "302.24399%"

      i18n.numberToPercentage(1000, { precision: null });
      // => "1000%"

      i18n.numberToPercentage("98a");
      // => "98a%"

      i18n.numberToPercentage(100, { format: "%n %" });
      // => "100.000 %"

      i18n.numberToPercentage(302.24398923423, { precision: 5, roundMode: "down" });
      // => "302.24398%"
    • Convert number to a formatted rounded value.

      Parameters

      • input: Numeric

        The number to be formatted.

      • Optionaloptions: Partial<NumberToRoundedOptions>

        The formatting options.

        • precision

          Sets the precision of the number (defaults to 3).

        • separator

          Sets the separator between the fractional and integer digits (defaults to ".").

        • roundMode

          Determine how rounding is performed.

        • significant

          If true, precision will be the number of significant_digits. If false, the number of fractional digits (defaults to false).

        • stripInsignificantZeros

          If true removes insignificant zeros after the decimal separator (defaults to false).

      Returns string

      The formatted number.

      i18n.numberToRounded(111.2345);
      // => "111.235"

      i18n.numberToRounded(111.2345, { precision: 2 });
      // => "111.23"

      i18n.numberToRounded(13, { precision: 5 });
      // => "13.00000"

      i18n.numberToRounded(389.32314, { precision: 0 });
      // => "389"

      i18n.numberToRounded(111.2345, { significant: true });
      // => "111"

      i18n.numberToRounded(111.2345, { precision: 1, significant: true });
      // => "100"

      i18n.numberToRounded(13, { precision: 5, significant: true });
      // => "13.000"

      i18n.numberToRounded(13, { precision: null });
      // => "13"

      i18n.numberToRounded(389.32314, { precision: 0, roundMode: "up" });
      // => "390"

      i18n.numberToRounded(13, {
      precision: 5,
      significant: true,
      stripInsignificantZeros: true,
      });
      // => "13"

      i18n.numberToRounded(389.32314, { precision: 4, significant: true });
      // => "389.3"

      i18n.numberToRounded(1111.2345, {
      precision: 2,
      separator: ",",
      delimiter: ".",
      });
      // => "1.111,23"
    • Add a callback that will be executed whenever locale/defaultLocale changes, or I18n#store / I18n#update is called.

      Parameters

      Returns () => void

      Return a function that can be used to unsubscribe the event handler.

    • Pluralize the given scope using the count value. The pluralized translation may have other placeholders, which will be retrieved from options.

      Parameters

      • count: number

        The counting number.

      • scope: Scope

        The translation scope.

      • Optionaloptions: TranslateOptions

        The translation options.

      Returns string

      The translated string.

    • Update translations by merging them. Newest translations will override existing ones.

      Parameters

      • translations: Dict

        An object containing the translations that will be merged into existing translations.

      Returns void

    • Formats time according to the directives in the given format string. The directives begins with a percent (%) character. Any text not listed as a directive will be passed through to the output string.

      Parameters

      • date: Date

        The date that will be formatted.

      • format: string

        The formatting string.

      • options: Partial<StrftimeOptions> = {}

        The formatting options.

      Returns string

      The formatted date.

      strftime

    • Reports the approximate distance in time between two time representations.

      Parameters

      Returns string

      The distance in time representation.

    • Converts the array to a comma-separated sentence where the last element is joined by the connector word.

      Parameters

      • items: any[]

        The list of items that will be joined.

      • options: Partial<ToSentenceOptions> = {}

        The options.

        • wordsConnector

          The sign or word used to join the elements in arrays with two or more elements (default: ", ").

        • twoWordsConnector

          The sign or word used to join the elements in arrays with two elements (default: " and ").

        • lastWordConnector

          The sign or word used to join the last element in arrays with three or more elements (default: ", and ").

      Returns string

      The joined string.

      i18n.toSentence(["apple", "banana", "pineapple"]);
      //=> apple, banana, and pineapple.
    • Convert the given dateString into a formatted date.

      Parameters

      • scope: Scope

        The formatting scope.

      • input: DateTime

        The string that must be parsed into a Date object.

      Returns string

      The formatted date.

    • Translate the given scope with the provided options.

      Type Parameters

      • T = string

      Parameters

      • scope: Scope

        The scope that will be used.

      • Optionaloptions: TranslateOptions

        The options that will be used on the translation. Can include some special options like defaultValue, count, and scope. Everything else will be treated as replacement values.

        • [key: string]: any
        • Optionalcount?: number
        • Optionaldefaults?: Dict[]
        • OptionaldefaultValue?: any
        • OptionalmissingBehavior?: string
        • Optionalscope?: Scope

      Returns string | T

      The translated string.

    • You may want to update a part of your translations. This is a public interface for doing it so.

      If the provided path exists, it'll be replaced. Otherwise, a new node will be created. When running in strict mode, paths that doesn't already exist will raise an exception.

      Strict mode will also raise an exception if the override type differs from previous node type.

      Parameters

      • path: string

        The path that's going to be updated. It must include the language, as in en.messages.

      • override: any

        The new translation node.

      • options: { strict: boolean } = ...

        Set options.

        • strict: boolean

          Raise an exception if path doesn't already exist, or if previous node's type differs from new node's type.

      Returns void

      i18n.update("en.number.format", {unit: "%n %u"});
      i18n.update("en.number.format", {unit: "%n %u"}, true);
    • Executes function with given locale set. The locale will be changed only during the callback's execution, switching back to the previous value once it finishes (with or without errors).

      This is an asynchronous call, which means you must use await or you may end up with a race condition.

      Parameters

      • locale: string

        The temporary locale that will be set during the function's execution.

      • callback: () => void

        The function that will be executed with a temporary locale set.

      Returns Promise<void>

      await i18n.withLocale("pt", () => {
      console.log(i18n.t("hello"));
      });