Skip to content

Back to Snippets

slugify()

A simple function for removing accents from Latin letters for producing URL parts, filenames, IDs, etc. It does not handle locale-specific transliterations (German umlauts, etc.), for which you’d need to reach for a more sophisticated library, such as sindresorhus/slugify.

/*
	1. decompose accented characters into their base character 
	   and combining diacritical mark.
	2. remove combining diacritical marks
	3. replace non-alphanumeric character sequences 
	   with single dashes
	4. remove trailing dashes
*/
function slugify(str) {
	return str
		.normalize('NFD') // 1.
		.replace(/[\u0300-\u036f]/g, '') // 2.
		.toLowerCase()
		.replace(/[^a-z0-9]+/g, '-') // 3.
		.replace(/(^\-)|(\-$)/g, ''); // 4.
}