Skip to main content

Slugify string

· One min read
Filip Tammergård
Software Engineer at Frilans Finans

When you generate URLs from titles, the title typically can't be used directly — spaces, question marks and other special characters don't belong in URL slugs. That's where a slugify function comes in handy.

This is the function I like to use:

const slugify = (str) => {
return str
.normalize("NFD")
.replace(/[̀-ͯ]/g, "")
.toLowerCase()
.trim()
.replace(/\s+/g, "-")
.replace(/[^\w\-]+/g, "")
.replace(/\-\-+/g, "-")
}

It does some cool stuff. Go ahead and test it out here: