How to HTML encode/escape a string? Is there a built-in?

kch picture kch · Mar 28, 2009 · Viewed 146.9k times · Source

I have an untrusted string that I want to show as text in an HTML page. I need to escape the chars '<' and '&' as HTML entities. The less fuss the better.

I'm using UTF8 and don't need other entities for accented letters.

Is there a built-in function in Ruby or Rails, or should I roll my own?

Answer

Christopher Bradford picture Christopher Bradford · Sep 30, 2010

Checkout the Ruby CGI class. There are methods to encode and decode HTML as well as URLs.

CGI::escapeHTML('Usage: foo "bar" <baz>')
# => "Usage: foo &quot;bar&quot; &lt;baz&gt;"