Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
CGI::Escape#unescapeHTML
(::string str) -> ::String
unescapeHTML(string)
lib/cgi/escape.rb
View on GitHub ↗
# File tmp/rubies/ruby-4.1.0-preview1/lib/cgi/escape.rb, line 113
def unescapeHTML(string)
enc = string.encoding
unless enc.ascii_compatible?
if enc.dummy?
origenc = enc
enc = Encoding::Converter.asciicompat_encoding(enc)
string = enc ? string.encode(enc) : string.b
end
string = string.gsub(Regexp.new('&(apos|amp|quot|gt|lt|#[0-9]+|#x[0-9A-Fa-f]+);'.encode(enc))) do
case $1.encode(Encoding::US_ASCII)
when 'apos' then "'".encode(enc)
when 'amp' then '&'.encode(enc)
when 'quot' then '"'.encode(enc)
when 'gt' then '>'.encode(enc)
when 'lt' then '<'.encode(enc)
when /\A#0*(\d+)\z/ then $1.to_i.chr(enc)
when /\A#x([0-9a-f]+)\z/i then $1.hex.chr(enc)
end
end
string.encode!(origenc) if origenc
return string
end
return string unless string.include? '&'
charlimit = case enc
when Encoding::UTF_8; 0x10ffff
when Encoding::ISO_8859_1; 256
else 128
end
string = string.b
string.gsub!(/&(apos|amp|quot|gt|lt|\#[0-9]+|\#[xX][0-9A-Fa-f]+);/) do
match = $1
case match
when 'apos' then "'"
when 'amp' then '&'
when 'quot' then '"'
when 'gt' then '>'
when 'lt' then '<'
else
# Numeric character reference. Decode into the binary buffer so that a
# non-ASCII byte already present in it never triggers an encoding
# compatibility error on concatenation; the trailing force_encoding
# re-tags the whole buffer. This mirrors the C extension's
# optimized_unescape_html.
n = match.start_with?('#x', '#X') ? match[2..-1].hex : match[1..-1].to_i
if n >= charlimit
"&#{match};" # out of range: keep the reference verbatim
elsif charlimit > 256
[n].pack('U').b # UTF-8: code point bytes, surrogates included (like rb_enc_mbcput)
else
n.chr.b # ISO-8859-1 / ASCII: single byte
end
end
end
string.force_encoding enc
end
Unescape a string that has been HTML-escaped
Example
CGI.unescapeHTML("Usage: foo "bar" <baz>") # => "Usage: foo \"bar\" <baz>"
See also
#unescape_html
#unescape_uri_component
#unescapeElement
#unescapeURIComponent
also in
4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0