DEV Community

Snappy Tools
Snappy Tools

Posted on Originally published at snappytools.app

Slugify Strings in JavaScript Without Breaking on Accents, Emoji, or Apostrophes

Most slug functions are one line of regex:

const slugify = s => s.toLowerCase().replace(/[^a-z0-9]+/g, '-');
Enter fullscreen mode Exit fullscreen mode

That line works for "Hello World" but fails on a lot of real titles. Here's what it does with a few of them:

Input Naive output What you wanted
Café & Crème Brûlée caf-cr-me-br-l-e cafe-and-creme-brulee
What's New in Node.js? what-s-new-in-node-js- whats-new-in-node-js
🚀 Launch Day! -launch-day- launch-day
Straße nach München stra-e-nach-m-nchen strasse-nach-munchen

Let's fix these one at a time.

1. Strip accents with Unicode normalization

String.prototype.normalize('NFD') splits an accented letter into its base letter followed by a combining mark. é becomes e + U+0301. Delete the marks and you're left with plain ASCII:

'Crème Brûlée'.normalize('NFD').replace(/[̀-ͯ]/g, '');
// 'Creme Brulee'
Enter fullscreen mode Exit fullscreen mode

U+0300–U+036F is the "Combining Diacritical Marks" block. That covers almost every accent used in European languages.

2. Handle the letters NFD can't split

Some letters aren't "letter + accent" in Unicode. They're separate letters, so normalization leaves them alone and the regex later deletes them. You need a small lookup table:

const TRANSLIT = {
  'ß': 'ss', 'æ': 'ae', 'Æ': 'AE', 'œ': 'oe', 'Œ': 'OE',
  'ø': 'o', 'Ø': 'O', 'đ': 'd', 'Đ': 'D', 'ð': 'd',
  'þ': 'th', 'ł': 'l', 'Ł': 'L', 'ı': 'i'
};
const TRANSLIT_RE = new RegExp(`[${Object.keys(TRANSLIT).join('')}]`, 'g');

'Straße, Øresund, Łódź'.replace(TRANSLIT_RE, c => TRANSLIT[c]);
// 'Strasse, Oresund, Lódź'
Enter fullscreen mode Exit fullscreen mode

Run this before the NFD step. The remaining ó and ź do decompose, so step 1 cleans them up.

3. Delete apostrophes instead of replacing them

If an apostrophe becomes a separator, don't turns into don-t. Remove apostrophes (straight and curly) before you split into words:

s.replace(/['’‘`]/g, '');
Enter fullscreen mode Exit fullscreen mode

4. Split into words, then join

If you split on non-alphanumeric runs and drop the empty pieces, you avoid leading, trailing, and doubled hyphens without any extra trimming:

const words = s.split(/[^a-z0-9]+/i).filter(Boolean);
const slug = words.join('-');
Enter fullscreen mode Exit fullscreen mode

Emoji, punctuation, and whitespace all count as separators, so 🚀 Launch Day! becomes ['Launch', 'Day'].

5. Optional: remove stop words, but never everything

Dropping words like the, a, and and of shortens slugs: the-complete-guide-to-css-grid becomes complete-guide-css-grid. Check that something is left afterwards, though. A title made up entirely of stop words would otherwise give an empty slug:

const STOP = new Set(['a','an','and','the','of','to','in','for','on','or','with']);
const kept = words.filter(w => !STOP.has(w.toLowerCase()));
if (kept.length) words = kept;
Enter fullscreen mode Exit fullscreen mode

6. Truncate at a word boundary

slug.slice(0, 50) can cut a word in half (complete-guide-to-resp). Cut at the last separator before the limit instead:

function truncate(slug, max, sep = '-') {
  if (slug.length <= max) return slug;
  const cut = slug.slice(0, max + 1);
  const at = cut.lastIndexOf(sep);
  return at > 0 ? cut.slice(0, at) : slug.slice(0, max);
}
Enter fullscreen mode Exit fullscreen mode

max + 1 is there because a separator sitting exactly at position max is a valid place to cut.

7. Non-Latin text: decide on purpose

With an ASCII-only regex, Привет мир becomes an empty string. That's a silent bug, not a slug. You have two options:

  • Keep Unicode letters. Use /[^\p{L}\p{N}\p{M}]+/gu as the split regex. You get привет-мир. Browsers display it fine, but it gets percent-encoded when copied.
  • Transliterate with a library such as transliteration or @sindresorhus/slugify if your URLs must be ASCII.

Either way, check for an empty result and fall back to something (an ID, a date) instead of publishing /blog/.

Putting it together

function slugify(text, { sep = '-', stopWords = false, max = 0 } = {}) {
  let s = text
    .replace(/&/g, ' and ')
    .replace(TRANSLIT_RE, c => TRANSLIT[c])
    .normalize('NFD').replace(/[̀-ͯ]/g, '')
    .toLowerCase()
    .replace(/['’‘`]/g, '');

  let words = s.split(/[^a-z0-9]+/).filter(Boolean);
  if (stopWords) {
    const kept = words.filter(w => !STOP.has(w));
    if (kept.length) words = kept;
  }
  const slug = words.join(sep);
  return max > 0 ? truncate(slug, max, sep) : slug;
}

slugify('Café & Crème Brûlée');          // 'cafe-and-creme-brulee'
slugify("What's New in Node.js?");       // 'whats-new-in-node-js'
slugify('🚀 Launch Day!');                // 'launch-day'
slugify('Straße nach München');          // 'strasse-nach-munchen'
slugify('The Complete Guide to CSS Grid', { stopWords: true });
                                         // 'complete-guide-css-grid'
Enter fullscreen mode Exit fullscreen mode

Test cases worth keeping

If you write your own slugify, put these in your test suite:

  • empty string, whitespace only, punctuation only ('!!!')
  • emoji only ('🚀🚀'). Should return '', and the caller should handle it
  • accents, ß, æ, ø, ł
  • apostrophes, both ' and ’
  • a title that's all stop words
  • a single word longer than your max length
  • duplicate titles. Your CMS needs -2, -3 suffixes, and the suffix has to fit inside the max length too

Don't want to write it?

I built a free Text to Slug Converter that does everything above in the browser. It also has batch mode (one title per line), unique suffixes for duplicates, a URL-prefix preview, and a Unicode mode. Nothing is uploaded. It's useful for checking what your own slugify function should return.

Top comments (0)