Unicode-Aware Slugify for URLs

Normalize accented text into clean URL slugs with NFKD decomposition, diacritic stripping, length limits and a safe fallback value.

JavascriptData Integrity

Code

snippet
const DIACRITICS = /[\u0300-\u036f]/g;

export function slugify(input, options = {}) {
  if (typeof input !== "string") throw new TypeError("input must be a string");
  const { maxLength = 80, separator = "-", fallback = "untitled" } = options;
  if (typeof separator !== "string" || separator.length === 0) {
    throw new TypeError("separator must be a non-empty string");
  }
  if (!Number.isInteger(maxLength) || maxLength < 1) {
    throw new RangeError("maxLength must be a positive integer");
  }
  const normalized = input.normalize("NFKD").replace(DIACRITICS, "").toLowerCase();
  const parts = normalized.split(/[^a-z0-9]+/).filter(Boolean);
  let slug = parts.join(separator);
  if (slug.length > maxLength) {
    slug = slug.slice(0, maxLength);
    const cut = slug.lastIndexOf(separator);
    if (cut > 0) slug = slug.slice(0, cut);
  }
  return slug || fallback;
}

console.log(slugify("Héllo, Wörld! 2026"));
console.log(slugify("  Café  au   Lait  "));
console.log(slugify("你好 世界"));
console.log(slugify("Express + TypeScript Guide", { maxLength: 18 }));