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

javascriptsnippet
26 lines
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 }));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

hello-world-2026
cafe-au-lait
untitled
express

How the snippet works

Unicode-Aware Slugify for URLs keeps everything in the function slugify.

A guard precedes the TypeError and RangeError: bad state stops the flow there instead of continuing.

What to watch for

  • The guard typeof input !== "string" short-circuits the flow with an early throw when its condition holds.

Using it

The primary signature is export function slugify(input, options = {})

slugify is what another module would consume; nothing else here is load-bearing for callers.

Key statements

if (typeof input !== "string") throw new TypeError("input must be a string");
throw new RangeError("maxLength must be a positive integer");
throw new TypeError("separator must be a non-empty string");

Interactive Tools for This Topic

FAQ

What happens if the preconditions do not hold?
Validation comes first — `TypeError` and `RangeError` marks the failure at `typeof input !== "string"`, before any partial work happens.
Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. The file defines `slugify` at load time.