JavaScript

i18n Minimal Translator

by @admin
12h ago
Apr 28, 2026
Public
A tiny internationalisation helper that loads a locale dictionary and resolves translation strings by dot-notation key. Supports variable interpolation via {{placeholder}} syntax. Falls back to the key itself when a translation is missing, keeping the UI readable during development. Swap the locale at runtime without a page reload.
JavaScript
function createI18n(locales, defaultLocale = 'en') {
  let locale = defaultLocale;

  function t(key, vars = {}) {
    const parts  = key.split('.');
    let   result = locales[locale] ?? locales[defaultLocale] ?? {};
    for (const part of parts) result = result?.[part];
    if (typeof result !== 'string') return key;
    return result.replace(/\{\{(\w+)\}\}/g, (_, k) => vars[k] ?? `{{${k}}}`);
  }

  return {
    t,
    setLocale: (l) => { locale = l; },
    getLocale: ()  => locale,
  };
}

// Usage
const i18n = createI18n({
  en: { greeting: 'Hello, {{name}}!', nav: { home: 'Home' } },
  es: { greeting: '¡Hola, {{name}}!', nav: { home: 'Inicio' } },
});

console.log(i18n.t('greeting', { name: 'Alice' })); // Hello, Alice!
i18n.setLocale('es');
console.log(i18n.t('greeting', { name: 'Alice' })); // ¡Hola, Alice!
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.