DevToolsForYou

HTML Escape Tool in Ruby — Code Examples

HTML Escape Tool in RubyUse the online tool →

HTML escaping converts special characters like <, >, &, and " into their HTML entity equivalents (&lt;, &gt;, &amp;, &quot;) to prevent XSS attacks and ensure correct rendering. Here is how to escape and unescape HTML in each language.

Ruby's CGI module provides CGI.escapeHTML and CGI.unescapeHTML. Rails adds the h helper and auto-escapes ERB output by default.

Ruby
require 'cgi'

raw = '<script>alert("xss")</script> & "quotes"'

# Escape
escaped = CGI.escapeHTML(raw)
puts escaped
# &lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt; &amp; &quot;quotes&quot;

# Unescape
unescaped = CGI.unescapeHTML("&lt;b&gt;Hello&lt;/b&gt; &amp; &quot;world&quot;")
puts unescaped # <b>Hello</b> & "world"

# In ERB templates (Rails/Sinatra), use the h() helper (alias for html_escape)
# <%= h(user_input) %>  → escaped
# <%= raw(trusted_html) %> → unescaped (only for trusted content)

# Rack::Utils.escape_html is also available in Sinatra/Rack apps
require 'rack'
puts Rack::Utils.escape_html(raw)
Notes & gotchas
  • In Rails ERB templates, <%= %> auto-escapes by default — use raw() or .html_safe only for trusted content.
  • CGI.escapeHTML escapes &, ", <, and > — note it does not escape single quotes by default.
  • Avoid String#html_safe in model/controller code; it is intended only for view helpers that return trusted HTML.
Try it in your browser

Need to html escape/unescape without writing code? The HTML Escape Tool runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open HTML Escape/Unescape
HTML Escape Tool in other languages