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?
Escaping in HTML means, that you are replacing some special characters with others. In HTML it means usally, you replace e. e.g < or > or " or & . These characters have special meanings in HTML.
escapeHtml4() [Apache Commons Text] This method takes the raw string as parameter and then escapes the characters using HTML entities. It supports all known HTML 4.0 entities.
Skipping > can potentially break code. You must keep in mind that inside the <> is also html. In that case skipping > will break. If you're only escaping for between tags then you probably only need escape < and &.
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" %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With