Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 446
kch Avatar asked Mar 28 '09 15:03

kch


People also ask

What is escaped in HTML?

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.

What is HTML escape in Java?

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.

How do I escape HTML data?

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 &.


2 Answers

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;" 
like image 91
Christopher Bradford Avatar answered Sep 18 '22 12:09

Christopher Bradford


The h helper method:

<%=h "<p> will be preserved" %> 
like image 29
Trevor Bramble Avatar answered Sep 18 '22 12:09

Trevor Bramble