How to HTML encode/escape a string? Is there a built-in?
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?
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 "bar" <baz>"
The h
helper method:
<%=h "<p> will be preserved" %>
In Ruby on Rails 3 HTML will be escaped by default.
For non-escaped strings use:
<%= raw "<p>hello world!</p>" %>
ERB::Util.html_escape can be used anywhere. It is available without using require
in Rails.
An addition to Christopher Bradford's answer to use the HTML escaping anywhere,
since most people don't use CGI
nowadays, you can also use Rack
:
require 'rack/utils'
Rack::Utils.escape_html('Usage: foo "bar" <baz>')