The Ultimate Way to Slugify a URL String in JavaScript
Turn “this URL-optimized string” into “this-url-optimized-string” easily with this snipped of JavaScript code.
With the advent of Node.js and modern application endpoint routing, I find it surprising that there is no in-built function to convert any string into an URL-optimized slug.
If your application users write content and you want to make their content searchable with an SEO-friendly URL, a slugify function is practically inevitable. I run my Node.js applications on DigitalOcean droplets. If you want to give it a try with a $100 credit, simply follow this link:
In order to turn an article’s original title “Why Uber isn’t spelled Über” into a slug optimized for URLs, parse your string through this slugify function to get “why-uber-isnt-spelled-uber”. I’ve pasted this Slugify function in a public Gist here.
Update 02/18/2019
This code snippet has been updated to include additional characters contributed by Christian Sarnataro and Paul Alexandru.
Update 06/29/2019
Added several more special characters.
Update 07/23/2019
Added special characters suggested by ahmet to support the Turkish language.