Slugify a string in JavaScript

By

Published · Updated

Tagged: JavaScript

Learn how to turn a string into a lowercase URL slug in JavaScript with the slugify package, including strict punctuation removal.

A slug is the part of a URL that identifies a page, made from its title. “Hello World, ça va?” becomes hello-world-ca-va.

The examples below use slugify 1.6.9 on Node 22.

Using the slugify package

Install the slugify library

npm i slugify

Then import it

import slugify from 'slugify'

and you can do

const slug = slugify('Testing this', {
  lower: true,
  strict: true
})

console.log(slug) // testing-this

lower converts the result to lowercase. strict removes characters other than letters, numbers, and the replacement character.

Why you want strict: true

Without options, slugify only replaces the spaces. Punctuation stays, and so does the uppercase:

slugify('Testing. this!') // 'Testing.-this!'
slugify('Testing. this!', { lower: true, strict: true }) // 'testing-this'

A dot or an exclamation mark in a URL is valid, but it’s not what you want in a slug. For URLs, pass both lower and strict.

You can also provide a remove regular expression when you need a custom rule:

slugify('Testing. this!', {
  lower: true,
  remove: /[*+~.,()'"!:@]/g
}) // 'testing-this'

The README says the regex should be a character class (the [...] part) with the g flag, otherwise it might not work as expected.

Accents and other alphabets

slugify turns accented letters into plain ones, and it knows some other alphabets:

slugify('Héllo Wörld, ça va?', { lower: true, strict: true }) // 'hello-world-ca-va'
slugify('Straße', { lower: true, strict: true }) // 'strasse'
slugify('Łódź', { lower: true, strict: true }) // 'lodz'
slugify('Привет мир', { lower: true }) // 'privet-mir'

Some symbols become words:

slugify('I ♥ Node & JS', { lower: true }) // 'i-love-node-and-js'
slugify('100% sure', { lower: true }) // '100percent-sure'

The locale option uses the rules of a specific language. In German, ä should become ae:

slugify('Ich mag Äpfel', { lower: true }) // 'ich-mag-apfel'
slugify('Ich mag Äpfel', { lower: true, locale: 'de' }) // 'ich-mag-aepfel'

Watch out: you can get an empty string

Characters that slugify doesn’t know are dropped. A title written in Japanese or Chinese gives you an empty slug:

slugify('日本語のタイトル', { lower: true }) // ''

The same happens with symbols it doesn’t know. C++ and C# both lose their symbols:

slugify('C++ and C#', { lower: true, strict: true }) // 'c-and-c'

You can teach it new characters with extend():

slugify.extend({ '+': 'plus', '#': 'sharp' })

slugify('C++ and C#', { lower: true, strict: true }) // 'cplusplus-and-csharp'

extend() changes the character map for the whole process, not just one call, so do it once at startup.

For titles in languages it can’t handle, always check for an empty result and fall back to something else, like an ID.

Other options

Duplicate slugs

Different titles can give the same slug. “Hello world”, “Hello, World!” and “hello world” are all hello-world. If you use slugs as URLs or database keys, add a number when the slug is taken:

import slugify from 'slugify'

function uniqueSlug(title, taken) {
  const base = slugify(title, { lower: true, strict: true }) || 'post'
  let slug = base
  let n = 2
  while (taken.has(slug)) slug = `${base}-${n++}`
  taken.add(slug)
  return slug
}

const taken = new Set()
uniqueSlug('Hello world', taken) // 'hello-world'
uniqueSlug('Hello, World!', taken) // 'hello-world-2'
uniqueSlug('hello world', taken) // 'hello-world-3'
uniqueSlug('日本語', taken) // 'post'

In a real app taken would be a lookup in your database, and you’d also want a unique index on the slug column, so 2 requests at the same time can’t save the same slug.

Slug generation is usually part of a URL contract. Avoid changing the algorithm after publishing URLs unless you also add redirects.

Without a library

If you only deal with Latin text, a few lines of plain JavaScript do the job:

function toSlug(str) {
  return str
    .normalize('NFD')
    .replace(/[̀-ͯ]/g, '')
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')
}

toSlug('Héllo Wörld, ça va?') // 'hello-world-ca-va'

normalize('NFD') splits a letter like é into e plus a separate accent mark, and the first replace() removes the accent marks. I explain this in the String normalize() method.

It’s not as smart as the library. Letters that aren’t “letter plus accent” get lost:

toSlug('Straße') // 'stra-e'
toSlug('Łódź') // 'odz'

slugify gives strasse and lodz for those. So use the library when your titles can contain any language.

If you just need to slugify a string once, without writing any code, use my slug generator tool.

Want me to talk about your product? You can sponsor this site.

Related posts about js: