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

PhotoLocationChanger
Easily change the location on your photos and videos
Click here for more info about the app
PhotoDateChanger
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