228

I am trying to decode some HTML entities, such as '&amp;lt;' becoming '<'.

I have an old gem (html_helpers) but it seems to have been abandoned twice.

Any recommendations? I will need to use it in a model.

3
  • 6
    Just found 'htmlentities' (htmlentities.rubyforge.org)
    – Kostas
    Oct 21, 2009 at 12:45
  • I should specify that I get the html from a bunch of different sites and need to save it as plain text in the database
    – Kostas
    Oct 26, 2009 at 13:18
  • 1
    While the most votes went to using CGI, don't. That's like pulling in all of Active Support to get a single method. Instead, use HTMLEntities, as mentioned in the selected answer. May 15, 2017 at 22:27

8 Answers 8

329

To encode the characters, you can use CGI.escapeHTML:

string = CGI.escapeHTML('test "escaping" <characters>')

To decode them, there is CGI.unescapeHTML:

CGI.unescapeHTML("test &quot;unescaping&quot; &lt;characters&gt;")

Of course, before that you need to include the CGI library:

require 'cgi'

And if you're in Rails, you don't need to use CGI to encode the string. There's the h method.

<%= h 'escaping <html>' %>
8
  • 9
    I tried this approach first but it does not turn entities like "&nbsp;" into " ". I guess I should specify that I get the html from a bunch of different sites and need to save it as plain text in the database.
    – Kostas
    Oct 26, 2009 at 12:59
  • 2
    If you are decoding HTML entities for storage as plain text in a database, then expect your database to do a lot of complaining about bad characters. Encoded entities are encoded to allow them to transfer as plain text. Decoding them can, and most likely will, revert them to upper-bit-set characters, AKA binary. Almost as likely, you could end up with multibyte characters which will really irritate a DB that is expecting plain text. You're better off decoding until nothing changes, then encode once so everything is normalized, then store them. Dec 1, 2010 at 21:13
  • 1
    I've encountered a lot of HTML with entities that have been encoded multiple times, really making a mess of things. Check out loofah; Its scrubbers were designed for this if I remember right. Dec 1, 2010 at 21:16
  • 3
    We have set our database to save Unicode so I doubt it will complain at all. And loofah is not what I am looking for, I don't want to get rid of the html tags - not at this point anyway.
    – Kostas
    Jan 11, 2011 at 0:46
  • 2
    it's 2015, unescapeHTML still omits some of the entities such as A acute
    – nurettin
    Jan 6, 2015 at 10:13
167

HTMLEntities can do it:

: jmglov@laurana; sudo gem install htmlentities
Successfully installed htmlentities-4.2.4
: jmglov@laurana;  irb
irb(main):001:0> require 'htmlentities'
=> []
irb(main):002:0> HTMLEntities.new.decode "&iexcl;I&#39;m highly&nbsp;annoyed with character references!"
=> "¡I'm highly annoyed with character references!"
2
57

I think Nokogiri gem is also a good choice. It is very stable and has a huge contributing community.

Samples:

a = Nokogiri::HTML.parse "foo&nbsp;b&auml;r"    
a.text 
=> "foo bär"

or

a = Nokogiri::HTML.parse "&iexcl;I&#39;m highly&nbsp;annoyed with character references!"
a.text
=> "¡I'm highly annoyed with character references!"
4
  • 3
    @theTinMan, yeah I think it depends on the demand. As you can see through the discussions in this topic, CGI.escapeHTML maybe unable to solve some cases. In the other hand, if you need a full set of support, I'm sure Nokogiri is a good choice.
    – Hoang Le
    Oct 9, 2015 at 4:30
  • 6
    Plus if you're already using Nokogiri for some HTML parsing, it's unreasonable to install yet another gem solely for that purpose. For instance, I'm using Sanitize gem for cleaning up HTML. Turns out this gem is using Nokogiri under the hood and so it'd be a shame not to take adventage of that. Thanks @HoangLe for the tip!
    – Tomalla
    Sep 7, 2016 at 10:40
  • 1
    Note: CGI::escapeHTML doesn't escape German characters like äöüß, and maybe more ... With Nokogiri I didn't checked yet, but this would be a plus point.
    – Beauty
    Apr 6, 2017 at 20:34
  • 1
    HTMLEntities would be a lightweight, and capable choice. I use Nokogiri a lot, and, unless I already have it loaded, I'd go with HTMLEntities. CGI is out of date. May 15, 2017 at 22:28
40

To decode characters in Rails use:

<%= raw '<html>' %>

So,

<%= raw '&lt;br&gt;' %>

would output

<br>
3
  • 5
    This only works in the view though. I need something that works in ActiveRecord too.
    – Kostas
    Jan 11, 2011 at 0:45
  • 4
    Just tested in debugger - raw '&lt br &gt' ==> '&lt br &gt'. Dec 14, 2011 at 12:36
  • 17
    #raw doesn't decode anything. It tells the view not to encode the string. It does this by wrapping the string in a ActiveSupport::SafeBuffer, which in turn has a flag (html_safe?), set to true. The view uses this flag to determine that the string can be injected directly into the HTML without being escaped. I like to think of html_safe as an indication by the programmer that the string in question has already been properly escaped. Nov 27, 2013 at 0:20
9

If you don't want to add a new dependency just to do this (like HTMLEntities) and you're already using Hpricot, it can both escape and unescape for you. It handles much more than CGI:

Hpricot.uxs "foo&nbsp;b&auml;r"
=> "foo bär"
2
  • 5
    Note for people looking at this now - Hpricot is no longer maintained. Jun 2, 2013 at 2:20
  • 2
    Use Nokogiri, which is the defacto standard for XML/HTML parsing, instead of Hpricot. Sep 2, 2014 at 22:32
0

You can use htmlascii gem:

Htmlascii.convert string
0

In Rails we can use: ERB::Util.html_escape and ERB::Util.url_encode.
In views, these are aliased as h and u

http://ruby-doc.org/stdlib-1.9.3/libdoc/erb/rdoc/ERB/Util.html

-4
<% str="<h1> Test </h1>" %>

result: &lt; h1 &gt; Test &lt; /h1 &gt;

<%= CGI.unescapeHTML(str).html_safe %>
2
  • I think that by adding html_safe on any user-entered text, you are telling the view that it is safe when it's possible that it's not safe. This would put your users at risk when they load that view. Oct 28, 2015 at 5:22
  • I don't know why so negative. I tried all solutions in this question. Only this works fine. About HTML safe, the user WANTS to render the HTML, then HTML_SAFE is correct. Sep 16, 2017 at 16:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.