Skip to content

Hreflang Tag Generator — JavaScript source

Turn a list of language versions into a valid hreflang set — locale normalization, duplicate detection and x-default handling — emitted as HTML link tags or an XML sitemap block.

This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// hreflang-tag-generator — pure locale-list validation + alternate-link
// emission (SEO/meta trio), the plain-JS twin of src/lib/hreflang.ts.
// Self-contained: the same normalizeLocale + buildHreflang grammar — ll/ll-CC
// case correction, row-located errors, x-default appended last, and both
// output flavors (HTML <link> block and XML sitemap <xhtml:link> block).

/** One locale/URL pair. Mirrors the TS HreflangRow interface. */
class HreflangRow {
  constructor(locale, url) {
    this.locale = locale;
    this.url = url;
  }
}

/**
 * Normalize a locale tag to Google's hreflang grammar: `ll` (ISO-639-1,
 * lowercase) or `ll-CC` (region uppercase, ISO-3166). Case and surrounding
 * whitespace are corrected (`en-us` → `en-US`); anything else is invalid
 * and returns null.
 */
export function normalizeLocale(raw) {
  const t = raw.trim();
  const single = /^([a-zA-Z]{2})$/.exec(t);
  if (single) return single[1].toLowerCase();
  const region = /^([a-zA-Z]{2})-([a-zA-Z]{2})$/.exec(t);
  if (region) return `${region[1].toLowerCase()}-${region[2].toUpperCase()}`;
  return null;
}

function validUrl(raw) {
  const t = raw.trim();
  return /^https?:\/\//.test(t) ? t : null;
}

/**
 * Validate a locale/URL table and emit both hreflang flavors. Invalid input
 * collects every error (row-located) and emits empty blocks; valid input
 * normalizes locales, preserves row order, and appends x-default last.
 */
export function buildHreflang(input) {
  const errors = [];
  const normalized = [];
  const seen = new Set();

  input.rows.forEach((row, i) => {
    const n = i + 1;
    const locale = normalizeLocale(row.locale ?? '');
    if (!locale) {
      errors.push(`Row ${n}: "${row.locale?.trim() ?? ''}" is not a valid locale — use ll or ll-CC (e.g. en, de-AT).`);
      return;
    }
    if (seen.has(locale)) {
      errors.push(`Row ${n}: locale "${locale}" is already used.`);
      return;
    }
    if (!row.url || !row.url.trim()) {
      errors.push(`Row ${n}: URL is required.`);
      return;
    }
    const url = validUrl(row.url);
    if (!url) {
      errors.push(`Row ${n}: URL must start with http:// or https://.`);
      return;
    }
    seen.add(locale);
    normalized.push(new HreflangRow(locale, url));
  });

  let xDefault = null;
  if (input.xDefaultUrl && input.xDefaultUrl.trim()) {
    xDefault = validUrl(input.xDefaultUrl);
    if (!xDefault) errors.push('x-default: URL must start with http:// or https://.');
  }

  if (errors.length > 0) {
    return { ok: false, errors, normalized: [], html: '', sitemap: '' };
  }

  const htmlLines = normalized.map(
    (r) => `<link rel="alternate" href="${r.url}" hreflang="${r.locale}" />`,
  );
  const sitemapLines = normalized.map(
    (r) => `    <xhtml:link rel="alternate" hreflang="${r.locale}" href="${r.url}"/>`,
  );
  if (xDefault) {
    htmlLines.push(`<link rel="alternate" href="${xDefault}" hreflang="x-default" />`);
    sitemapLines.push(`    <xhtml:link rel="alternate" hreflang="x-default" href="${xDefault}"/>`);
  }

  return {
    ok: true,
    errors: [],
    normalized,
    html: htmlLines.join('\n'),
    sitemap: sitemapLines.join('\n'),
  };
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →