· 1 min read

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).

Comments

Leave a comment