josh josh - 1 year ago 71
Ruby Question

How could I use a regex expression in Ruby to ignore html tags?

I have a Blog ActiveRecord model in a rails application. The body property is text. It includes html tags for images, headings etc.. I want to create a method that takes the first n amount of text of the body to show on the index page as preview text. The problem is my method also grabbed all of the html tags so my method returns a string that looks like this.

Here is a picture I am talking about. <img src="path/to/image.png" / > <h1> Nice </h1>

Is there regex solution to ignore all the tags?

Answer Source

Rails has a strip_tags method

strip_tags("Strip <i>these</i> tags!")
# => Strip these tags!

strip_tags("<b>Bold</b> no more!  <a href='more.html'>See more here</a>...")
# => Bold no more!  See more here...

strip_tags("<div id='top-bar'>Welcome to my website!</div>")
# => Welcome to my website!
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download