Barefoot Development

Regex to display X words in Rails

I just created a useful combination of regex's in Ruby on Rails and wanted to share (and remember). I needed to display a summary of an article, as the first group of words from a string that might contain HTML, start with garbage, or otherwise not be pretty.

So, I stripped the HTML, removed non-printable stuff from the beginning, and came up with this to show the first 40 words of the article's body:

article.body.gsub(/<\/?[^>]*>/, "").gsub(/^\W*/, "")[/([\S]*[\W]*){40}/]

Enjoy! (Or, leave a comment with a better way to do it.)

Doug Smith, Senior Developer, Barefoot

Labels: ,


  1. Blogger Doug Smith said:  

    I was reminded by a very bright co-worker to be sure to look in Rails' texthelper class to see all the magic that is there. (I'm so used to doing my own regexes from other languages/frameworks that I sometimes don't think to look for the Rails freebies.) So, my previous code could be simplified to:


    Thanks, Bobby!

Post a Comment

« Home