Formatting Strings for URLs

Here’s a quick Ruby snippet you can use to format a string to be used in a URL:

string.downcase.gsub(/[^a-z0-9]+/i, '_').chomp('_')

This turns something like

This is a Post URL!

into

this_is_a_post_url

which you can use in your archive URLs (like http://www.website.com/article/this_is_a_post_url)

The string is first converted to all lowercase letters with the downcase method of the String class.

Next, we use gsub to strip out everything that isn’t a letter or a number (including spaces) using regular expressions. We replace each of the gaps with a URL friendly separator, the ‘_‘ underscore character. You could also use some other character, like a hyphen, if you prefer.

Finally, since our formatted string could end with a separator character, we chomp that off the end.