arkanciscan arkanciscan - 1 year ago 307
HTML Question

Is there an HTML safe truncate method in Rails?

I have a string of HTML in Rails. I'd like to truncate the string after a certain number of characters not including the HTML markup. Also, if the split happens to fall in the middle of an opening and closing tag, I'd like to close the open tag/s. For example;

html = "123<a href='#'>456</a>7890"
truncate_markup(html, :length => 5) --> "123<a href='#'>45</a>"

Answer Source

There are two completely different solutions both with the same name: truncate_html

  1. : This is a gem and uses an html parser (nokogiri)
  2. : This is a file you put in your helpers directory. It uses regular expressions and has no dependencies.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download