DEV Community

desgh white
desgh white

Posted on

Building a Locale-Aware Slug Generator That Handles Spanish Accents

URL slugs for Spanish-language content break if you just call .toLowerCase().replace(/\s+/g, '-'). The accented characters á é í ó ú ñ ü are valid UTF-8 but most slug generators strip them, producing unreadable URLs or, worse, collisions (año and ano are different words).

Normalise, then map

The standard approach uses Unicode NFD decomposition to separate base letters from combining marks, then drops the marks:

function slugify(text) {
  return text
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')  // strip combining marks
    .replace(/ñ/gi, 'n')               // ñ decomposes differently
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-|-$/g, '');
}
Enter fullscreen mode Exit fullscreen mode

The ñ special-case matters: NFD splits ñ into n + combining tilde, but some fonts and copy-paste paths deliver a precomposed ñ (U+00F1) that survives the regex. Handling both is safer.

Collision detection

Two distinct Spanish phrases can produce the same slug after stripping. A content platform like bonus at Casinito that serves a Latin American audience needs a uniqueness check at insert time, appending a numeric suffix when a collision is found:

async function uniqueSlug(base, existing) {
  let candidate = base;
  let i = 1;
  while (existing.has(candidate)) candidate = `${base}-${++i}`;
  return candidate;
}
Enter fullscreen mode Exit fullscreen mode

SEO note

Google handles UTF-8 slugs fine, but many analytics tools and affiliate trackers silently truncate or encode them. If your stack includes third-party tracking, ASCII-safe slugs avoid a whole class of broken attribution.

Top comments (0)