Ruby: Escape, Unescape, Encode, Decode, HTML, XML, URI, URL
Join the DZone community and get the full member experience.
Join For FreeThis example will show you how to escape and un-escape a value to be included in a URI and within HTML.
require 'cgi'
# escape
name = "ruby?"
value = "yes"
url = "http://example.com/?" + CGI.escape(name) + '=' + CGI.escape(value) + "&var=T"
# url: http://example.com/?ruby%3F=yes&var=T
html = %(example)
# html: example
# unescape
name_encoded = html.match(/http:([^"]+)/)[0]
# name_encoded: http://example.com/?ruby%3F=yes&var=T
href = CGI.unescapeHTML(name_encoded)
# href: http://example.com/?ruby%3F=yes&var=T
query = href.match(/\?(.*)$/)[1]
# query: ruby%3F=yes&var=T
pairs = query.split('&')
# pairs: ["ruby%3F=yes", "var=T"]
name, value = pairs[0].split('=').map{|v| CGI.unescape(v)}
# name, value: ["ruby?", "yes"]
XML
HTML
Uniform Resource Identifier
Opinions expressed by DZone contributors are their own.
Comments