This post originated from an RSS feed registered with Ruby Buzz
by Matthew Bass.
Original Post: Surrounding text with a tag using Ruby’s gsub
Feed Title: Pelargir
Feed URL: http://feeds.feedburner.com/pelargir/
Feed Description: Musings on software and life from Matthew Bass. Regular posts on new web products, tips and tricks, etc.
Here’s how to identify a keyword in a block of text using a case-insensitive regular expression, and surround that keyword with an HTML tag:
text = "hello world, this is a test"
text.gsub!(/(WORLD)/i, "<b>\1</b>")
The following string is produced:
hello <b>world</b>, this is a test
Note that \\1 references the group in the regex (surrounded by parens). This results in [...]