Skip to content
Daily Web Lab

Why the JavaScript Slugify Function You Copied Loses Letters

The JavaScript slugify function everyone publishes handles French perfectly and quietly deletes letters from Danish, Polish and Turkish names. Here is the measurement, the reason, and a version that does not.

By Umair Nazir ·

Every result for this search gives you the same function. I read ten of them on 2026-10-21 and the code is near-identical across sitelint.com, the widely forked codeguy gist, GeeksforGeeks, byby.dev and six others. Here it is, in the shape they publish it.

the JavaScript slugify function everyone publishes

const slugify = (str) =>
  str
    .toString()
    .normalize('NFD')                 // split letters from their accents
    .replace(/[\u0300-\u036f]/g, '')  // drop the accent marks
    .toLowerCase()
    .trim()
    .replace(/\s+/g, '-')             // spaces to hyphens
    .replace(/[^\w-]+/g, '')          // drop anything else
    .replace(/--+/g, '-');            // collapse repeats

It is clean, dependency-free, and several of those pages recommend it specifically as the way to handle accented text. For French and Spanish that is true. I ran twelve strings through it to check the rest.

LanguageInputOutputIntact
FrenchBeyoncé à Cafébeyonce-a-cafeyes
SpanishEl Niñoel-ninoyes
GermanStraße und Fußballstrae-und-fuballno
DanishSøren i Ølstykkesren-i-lstykkeno
PolishŁódź i Gdańskodz-i-gdanskno
CroatianĐakovoakovono
TurkishDiyarbakırdiyarbakrno
IcelandicÞingvelliringvellirno
LigatureEncyclopædiaencyclopdiano
VietnameseĐà Nẵnga-nangno
SwedishVäxjö och Årevaxjo-och-areyes
German umlautHöhlen überhohlen-uberyes
All twelve strings through the canonical one-liner. Eight lose at least one letter outright. Reproduce every row with scripts/measure-slugs.mjs.

Eight of the twelve lost letters. Not transliterated into something imperfect. Deleted, with no error thrown and nothing logged. A Danish name came out as sren-i-lstykke, and if that had gone into a database column it would have stayed there.

Why NFD cannot reach those letters

Worth understanding rather than patching, because the gap is structural and adding cases one at a time will not close it.

Unicode normalisation form D rewrites a precomposed character as its base letter followed by a separate combining mark. The e-acute in Beyoncé becomes a plain e plus U+0301, and since every combining mark lives in the block from U+0300 to U+036F, one regular expression removes the lot. That is genuinely elegant, and it is why the snippet spread.

The catch is the word decompose. A character only has a decomposition if Unicode defines one, and many letters are not an accented version of anything. The German sharp s is its own letter. So is the Danish slashed o, the Polish barred l, the Croatian barred d, the Turkish dotless i, and the Icelandic thorn and eth. None of them is a Latin letter wearing a hat.

node

'é'.normalize('NFD').length   // 2  -> e + U+0301, the regex catches it
'ß'.normalize('NFD').length   // 1  -> unchanged, nothing to catch
'ø'.normalize('NFD').length   // 1
'ł'.normalize('NFD').length   // 1
'ı'.normalize('NFD').length   // 1

So those letters pass through the normalise step untouched and arrive at the line that removes anything outside [\w-]. They are not word characters, so they are stripped as though they were punctuation. The function is working exactly as written; the assumption behind it is what is wrong.

A version that keeps every letter

Transliterate from an explicit table first, then let NFD mop up the accents it genuinely handles. Order matters: the table has to run before normalisation, or an umlaut will already have lost its dots by the time you look it up.

slugify.js

// Letters with no Unicode decomposition. These are exactly the ones
// NFD cannot help with, so they need stating explicitly.
const TRANSLITERATE = {
  'ß': 'ss', 'ø': 'o', 'Ø': 'O', 'ł': 'l', 'Ł': 'L',
  'đ': 'd', 'Đ': 'D', 'ı': 'i', 'İ': 'I',
  'þ': 'th', 'Þ': 'Th', 'ð': 'd', 'Ð': 'D',
  'æ': 'ae', 'Æ': 'AE', 'œ': 'oe', 'Œ': 'OE',
  // German expands rather than strips: a passport spells it muenchen.
  'ä': 'ae', 'ö': 'oe', 'ü': 'ue',
  'Ä': 'Ae', 'Ö': 'Oe', 'Ü': 'Ue',
};

export function slugify(input) {
  const mapped = [...String(input)]
    .map((ch) => TRANSLITERATE[ch] ?? ch)
    .join('');

  return mapped
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')   // one class, so no stray characters survive
    .replace(/^-+|-+$/g, '');      // trim separators from both ends
}

Two smaller changes came with it. Collapsing everything that is not a lowercase letter or digit into a single hyphen removes the need for the separate space and repeat-collapsing passes, and it closes a hole in the original: [^\w-] permits the underscore, because the underscore is a word character, so and__underscores survives the original function intact. The trim on the last line is then required rather than tidy: collapsing punctuation into a hyphen instead of deleting it means a title that starts or ends with punctuation would otherwise keep a stray separator there.

Add Cyrillic and Greek to the table if you need them. Both are well-defined, mechanical mappings. One warning from building the same thing for the tool on this site: if you write those tables by hand, write the capitals too. I listed Cyrillic in lowercase only on the first pass, and Moscow in Cyrillic came out as oskva, having silently lost its capital M. Deriving the uppercase half from the lowercase one in code is the fix that cannot drift.

Or use a library, and know which one you picked

For anything beyond a side project, take a maintained package. It will cover scripts your table never will. What it will not do is give you the answer, because transliteration has several defensible answers and the popular packages picked different ones. I installed three and ran the same strings through them.

“Höhlen über München”

  • one-liner → hohlen-uber-munchen
  • slugify → hohlen-uber-munchen
  • @sindresorhus/slugify → hoehlen-ueber-muenchen
  • speakingurl → hoehlen-ueber-muenchen

“Þingvellir og Jökulsárlón” with a capital thorn: four implementations, four results

  • one-liner → ingvellir-og-jokulsarlon
  • slugify → thingvellir-og-jokulsarlon
  • @sindresorhus/slugify → t-hingvellir-og-joekulsarlon
  • speakingurl → thingvellir-og-joekulsarlon

“Đakovo”, Croatian barred d

  • slugify → djakovo
  • @sindresorhus/slugify → dakovo
  • speakingurl → dakovo
Three maintained packages and the one-liner, identical input. Versions: slugify 1.6.9, @sindresorhus/slugify 3.0.1, speakingurl 14.0.1, measured 2026-10-21 on Node 20.19.6.

The German row is a convention split, not a defect. German expands an umlaut, which is why a passport spells Munich muenchen, and two of the three packages follow that. The Croatian row is the same kind of disagreement: dj is the standard romanisation of that letter, and a plain d is the lazier but common choice.

Pick one deliberately, then do not change it. Slugs are permanent once they are indexed, and swapping libraries mid-project quietly rewrites the URLs of everything published afterwards while leaving the earlier ones alone.

The third row is a bug, and it took narrowing down

Look again at t-hingvellir. A hyphen has appeared inside the first word, which no convention asks for. I tested the letter on its own to find out why.

node

import slugify from '@sindresorhus/slugify';  // 3.0.1

slugify('Þingvellir')   // 't-hingvellir'
slugify('þingvellir')   // 'thingvellir'   <- lowercase is fine
slugify('Þ')            // 'th'
slugify('Þór')          // 't-hor'
slugify('Þakka')        // 't-hakka'

Capital thorn transliterates to the two characters Th. The package then splits camel case into separate words, and a capital T followed by a lowercase h looks exactly like a camel-case boundary, so it inserts a separator. Lowercase thorn never triggers it because there is no capital to find.

This is the kind of defect that lives in a library for years. Reaching it needs a title that begins with a capital thorn, which in practice means Icelandic content, and Icelandic is roughly 400,000 speakers. Worth checking your own language against whatever you choose, instead of assuming the test suite covered it.

Two traps the snippet cannot warn you about

Both of these bite in a real codebase and never in a tutorial, because a tutorial slugifies one string and stops.

Collisions are inevitable, and usually hit a unique column

Slugification throws information away, so different titles land on the same slug. “Node.js vs Deno” and “Node JS vs Deno!” both reduce to node-js-vs-deno. If that column is unique, the second insert fails; if it is not, you have two rows fighting over one URL. Handle it where you write, not where you slugify.

unique slug on write

async function uniqueSlug(title, exists) {
  const base = slugify(title);
  if (!(await exists(base))) return base;

  // Suffix from 2, because "-1" reads like the first of a series.
  for (let n = 2; n < 100; n += 1) {
    const candidate = `${base}-${n}`;
    if (!(await exists(candidate))) return candidate;
  }
  throw new Error(`No free slug for "${base}" after 99 attempts`);
}

toLowerCase is locale-dependent, and one locale disagrees

Turkish treats the dotted and dotless i as separate letters, so a capital I lowercases to the dotless form rather than the one every other language expects.

node

'I'.toLowerCase()                // 'i'
'I'.toLocaleLowerCase('tr')      // 'ı'   U+0131, dotless

// So on a Turkish locale this returns 'ıstanbul', not 'istanbul':
'ISTANBUL'.toLocaleLowerCase()

Plain toLowerCase() is not affected, since it ignores locale by design. The danger is toLocaleLowerCase(), which some codebases reach for believing it to be the more correct choice. For slugs it is the wrong one: a URL should not change shape according to the server’s locale. Keep toLowerCase(), and let the transliteration table turn the dotless i into a plain i.

What to take away

A JavaScript slugify function is twelve lines of code that looks finished long before it is. If your content is English, French or Spanish, the one-liner is fine and this whole article is theoretical. The moment a title arrives in German, Danish, Polish, Croatian, Turkish, Icelandic or Vietnamese, it starts deleting letters from names, and it does so without complaint.

Transliterate from an explicit table before normalising, or take a maintained package and check it against your own language first. Then leave it alone, because the one thing more expensive than a wrong slug is a slug that changes after it has been indexed.

Frequently asked questions

What is the best JavaScript slugify function?

One that transliterates from an explicit table before it normalises, rather than relying on NFD alone. NFD only reaches characters that decompose into a base letter plus an accent, so letters like the German sharp s, Danish slashed o, Polish barred l and Turkish dotless i pass through it untouched and are then deleted by the catch-all that follows. Measured across ten test strings on 2026-10-21, the widely published one-liner lost letters in eight of them. The version in this article maps those letters first, which fixes the cause rather than the symptom.

Why does my slugify function remove German or Danish characters?

Because normalize('NFD') cannot decompose them, and the next line removes anything that is not a word character. The sharp s, slashed o, barred l, barred d, dotless i, thorn, eth and the ae and oe ligatures are independent letters in Unicode rather than accented variants, so there is no combining mark to strip and nothing matches. They reach the final replace as unrecognised characters and are discarded like punctuation, silently. Straße becomes strae and Søren becomes sren.

Should I use the slugify npm package or write my own?

Use a package for anything you will maintain, since it covers scripts a hand-written table will not. Just know that packages disagree. Measured on 2026-10-21, slugify 1.6.9 renders Höhlen über München as hohlen-uber-munchen while @sindresorhus/slugify 3.0.1 and speakingurl 14.0.1 both render it hoehlen-ueber-muenchen, following the German convention of expanding umlauts. Pick one deliberately and stay on it, because switching rewrites the slugs of everything published afterwards.

How do I handle duplicate slugs?

Check for the collision at write time and append a numeric suffix, rather than trying to make the slug function itself unique. Slugification discards information, so distinct titles genuinely do collide: 'Node.js vs Deno' and 'Node JS vs Deno!' both reduce to node-js-vs-deno. Query for the base slug, and if it is taken try base-2, base-3 and so on. Starting at 2 reads more naturally than a -1 suffix on the second item.

Does normalize('NFKD') work better than NFD for slugs?

It reaches a few more characters but it is not a fix. NFKD applies compatibility decomposition, so it will turn a ligature like fi into f and i, and convert superscripts and some full-width forms. It still does not decompose the sharp s, slashed o, barred l or dotless i, because those have no decomposition of either kind. NFKD also makes changes you may not want in a URL, such as rewriting typographic forms. An explicit table remains necessary either way.

Should slugs be lowercase?

Yes, by convention and for a practical reason: URL paths are case-sensitive on most servers, so /About and /about can be two different pages serving identical content, which is a duplicate-content problem you get for free by accident. Lowercasing everything at generation time avoids it. Use toLowerCase rather than toLocaleLowerCase, since the locale-aware version turns a capital I into a dotless one on a Turkish locale and a URL should not depend on server configuration.

Ready to try it? Open the URL Slug Generator — it runs entirely in your browser.

The tools here run entirely in your browser and need no cookies. We would like to use cookies only for advertising and traffic measurement, which help keep the site free. Read our privacy policy.