Search code examples
rubysanitize

Ruby Sanitize Code ... why is & sanitized


I currently use the following code to sanitize a string before storing them:

ERB::Util::h(string)

My problem occurs when the string has been sanitized already like this:

string = "Watching baseball `&` football"

The sanitized string will look like:

sanitized_string = "Watching baseball `&` football"

Can I sanitize by just turning < into &lt; and > into &gt; via substitution?


Solution

  • Unescape first, then escape again:

    require 'cgi'
    string = "Watching baseball &amp; football"
    
    CGI.escapeHTML(CGI.unescapeHTML(string))
    
    => "Watching baseball &amp; football"