htmlruby-on-railsescaping

How to html escape special character on rails


I want to parse special characters (read from a file) to HTML format. For example

**üö ä€ afd sdf sdfüäää** 

to

<p>&uuml;&ouml; &auml;&euro; afd sdf sdf&uuml;&auml;&auml;&auml;&nbsp;<br />&nbsp;</p>

I found few solution on web:

Rack::Utils.escape_html()

CGI::escapeHTML()

ERB::Util.html_escape()

Each of them is doing fine with normal text:

HI"ksdlfj</?>>>.dsfklsd

to

<p>HI"ksdlfj&lt;/?&gt;&gt;&gt;.dsfklsd</p>

But it doesn't do anything, when I have those special characters in input text.

Any help on this?

Rails Version: 3.0.5
Ruby: ruby 1.9.3p429

Solution

  • you can use htmlentities

    require 'htmlentities'
    str = "üö ä€ afd sdf sdfüäää"
    HTMLEntities.new.encode(str, :named)
    
    #=> "&uuml;&ouml; &auml;&euro; afd sdf sdf&uuml;&auml;&auml;&auml;"