JavaScript ECMAScript 6 slugify

I wanted to slugify a URL using Javascript.  There are lots of implementations out there, but they aren’t very nice.  I have taken inspiration from the Django implementation to create the following.  It uses String.prototype.normalize(), which is ES6, so it won’t work where you don’t have ES6.  I’m using Node.js, so I’m happy with this, and it’s very neat.  
function slugify(value) {
// Compatibly-decompose and remove combining characters.
value = value.normalize('NFKD').replace(/[\u0300-\u036F]/g, '');
// Remove all non-word characters, leaving spaces and dashes. Trim and convert to lower case.
value = value.replace(/[^\w\s\-]+/g, '').trim().toLowerCase();
// Replace groups of spaces and dashes with a single dash.
return value.replace(/[-\s]+/g, '-');
The following runs some test cases through it.  They are designed for a different function, so most fail, but it shows how it works.  

Leave a Reply

Your email address will not be published. Required fields are marked *