SQLTerminal.app
now available

XPath.app
now available
Want fresh tech tips in your inbox?

A Regular Expression to Generate Dash Separated Slugs AKA Pretty URLs

       

This regular expression matches non alphanumeric characters in a string.


r = /[^a-z0-9]{1,}/i

You can use it to create URL friendly slugs.


 slug = "hello world!".gsub(/[^a-z0-9]{1,}/i, '-').downcase # => hello-world

In combination with String#gsub it will replace the non alphanumeric characters with a dash "-" ... or anything you want.

The important bit here is the {1,} in the regular expression. This prevents URLs from having multiple dashes when multiple non alpha numeric characters are found next to each other.

For instance,

"hello, world" should be "hello-world" and not "hello--world" (two dashes in the latter).

Tagged w/ #regular expressions #ruby #strings

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
VocabReminder
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
VocabQuiz
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app