Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I encode/decode HTML entities in Ruby?

Tags:

html

ruby

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.

like image 200
Kostas Avatar asked Oct 21 '09 12:10

Kostas


People also ask

What is HTML entity decode?

HTML encoding converts characters that are not allowed in HTML into character-entity equivalents; HTML decoding reverses the encoding. For example, when embedded in a block of text, the characters < and > are encoded as &lt; and &gt; for HTTP transmission.

How do I encode HTML?

Load the data to HTML–encode from a file, then press the 'Encode' button: Browse: Alternatively, type or paste in the text you want to HTML–encode, then press the 'Encode' button.

How do I decode HTML files?

Wikipedia has a good expalanation of character encodings and how some characters should be represented in HTML. Load the HTML data to decode from a file, then press the 'Decode' button: Browse: Alternatively, type or paste in the text you want to HTML–decode, then press the 'Decode' button.

Can you decode HTML?

HTML DecodeThe encoded characters are converted back to their original form in the decoding process. It decodes a string that contains HTML numeric character references and returns the decoded string. You can also choose to convert HTML code into JavaScript string.


2 Answers

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>' %> 
like image 136
Damien MATHIEU Avatar answered Oct 03 '22 03:10

Damien MATHIEU


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!" 
like image 25
Ivailo Bardarov Avatar answered Oct 03 '22 04:10

Ivailo Bardarov