DocsCore

Locale utilities

Validate, normalize, describe and match BCP 47 locale codes with @generic-translation/core.

On this page

@generic-translation/core is the zero-dependency base of every other Generic Translation package. It runs in browsers, Node 20+ and Workers. The locale helpers are thin layers over the platform’s Intl APIs, so their answers come from the CLDR data in your JavaScript runtime.

@generic-translation/core is not published to npm yet; see the introduction for building it from source.

import { determineLocale, getLocaleProperties, standardizeLocale } from "@generic-translation/core";

Constants

Export Value
DEFAULT_SOURCE_LOCALE "en"
DEFAULT_BASE_URL "https://generic-translation-api.jacobfv123.workers.dev"
SUPPORTED_LOCALES An array of 100+ common locale codes. See the full table.

SUPPORTED_LOCALES is a convenience list for pickers and defaults, not a restriction. Any valid BCP 47 tag works throughout the libraries.

isValidLocale(locale)

Returns true when the string is a well-formed BCP 47 tag whose language, and region and script if present, are known to the runtime.

isValidLocale("pt-BR");  // true
isValidLocale("en_US");  // false (not BCP 47: run standardizeLocale first)
isValidLocale("xx-YY");  // false
isValidLocale("");       // false

standardizeLocale(locale)

Returns the canonical form of a code. Input that cannot be parsed is returned trimmed and otherwise unchanged.

standardizeLocale("en_us");       // "en-US"
standardizeLocale("ZH-hans-cn");  // "zh-Hans-CN"

getLocaleProperties(locale, displayLocale?)

Everything you need to build a language picker. displayLocale (default "en") is the language the names are written in.

getLocaleProperties("fr-CA");
{
  "code": "fr-CA",
  "name": "Canadian French",
  "nativeName": "Français canadien",
  "languageCode": "fr",
  "languageName": "French",
  "regionCode": "CA",
  "regionName": "Canada",
  "emoji": "🇨🇦",
  "direction": "ltr"
}
interface LocaleProperties {
  code: string;          // canonical code
  name: string;          // in displayLocale
  nativeName: string;    // in the locale itself
  languageCode: string;
  languageName: string;
  regionCode?: string;
  regionName?: string;
  scriptCode?: string;
  emoji: string;         // flag, or a globe when no region can be inferred
  direction: "ltr" | "rtl";
}

getLocaleName(locale, displayLocale?)

The human-readable name alone.

getLocaleName("de");        // "German"
getLocaleName("de", "fr");  // "allemand"
getLocaleName("ja", "ja");  // "日本語"

getLocaleEmoji(locale)

A flag emoji. Uses the explicit region when there is one, otherwise the most likely region for the language, and falls back to a globe.

getLocaleEmoji("pt-BR");  // "🇧🇷"
getLocaleEmoji("ja");     // "🇯🇵"

Flags are a convenient visual hint and a poor identifier for languages: many languages span countries and many countries have several languages. Always show the name next to the flag.

getLocaleDirection(locale)

"rtl" for locales written in right-to-left scripts, otherwise "ltr".

getLocaleDirection("ar");  // "rtl"
getLocaleDirection("he");  // "rtl"
getLocaleDirection("en");  // "ltr"
<html lang={locale} dir={getLocaleDirection(locale)}>

isSameLanguage(a, b)

true when two codes share a language, regardless of region.

isSameLanguage("en-US", "en-GB");  // true
isSameLanguage("pt", "es");        // false

requiresTranslation(source, target, approved?)

Whether content written in source needs translating to be shown in target. It is false when both resolve to the same dialect, when target is not a usable locale, or when approved is given and target matches none of the approved locales.

requiresTranslation("en", "en-US");               // false: same dialect
requiresTranslation("en", "fr");                  // true
requiresTranslation("en", "fr", ["es", "de"]);    // false: fr is not approved

The libraries use this to decide whether to look anything up at all for the current locale.

determineLocale(requested, supported, fallback?)

Picks the best entry of supported for what the user asked for. requested is one code or a list in preference order. For each requested locale in turn it prefers an exact match, then the same language and region, then the same language. It returns the entry from supported exactly as you wrote it, or fallback (default undefined) when nothing matches.

determineLocale("fr-CA", ["en", "fr", "de"]);               // "fr"
determineLocale(["sv", "en-GB"], ["en-US", "de"]);          // "en-US"
determineLocale("ja", ["en", "fr"], "en");                  // "en"

parseAcceptLanguage(header)

Parses an Accept-Language header into canonical codes ordered by preference (q-value, then position). Wildcards, entries with q=0 and unparseable entries are dropped.

parseAcceptLanguage("fr-CH, fr;q=0.9, en;q=0.8, *;q=0.5");
// ["fr-CH", "fr", "en"]

Combine it with determineLocale to negotiate a locale on the server:

const locale = determineLocale(
  parseAcceptLanguage(request.headers.get("accept-language") ?? ""),
  ["en", "es", "fr"],
  "en",
);

Something wrong or unclear on this page? Open an issue.

Type to search the documentation.