Un-Escape

A JS un-escaper for HTML

HTML

<p id="escaped"></p>
<p id="unescaped"></p>

CoffeeScript

String::unescape = (strict = false) ->
  ###
  # Take escaped text, and return the unescaped version
  #
  # @param string str | String to be used
  # @param bool strict | Stict mode will remove all HTML
  #
  # Test it here:
  # https://jsfiddle.net/tigerhawkvok/t9pn1dn5/
  ###
  # Create a dummy element
  element = document.createElement("div")
  decodeHTMLEntities = (str) ->
    if str? and typeof str is "string"
      unless strict is true
        # escape HTML tags
        str = escape(str).replace(/%26/g,'&').replace(/%23/g,'#').replace(/%3B/g,';')
      else
        str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '')
        str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '')
      element.innerHTML = str
      if element.innerText
        # Do we support innerText?
        str = element.innerText
        element.innerText = ""
      else
        # Firefox
        str = element.textContent
        element.textContent = ""
    str = unescape(str)
    str
  # Remove encoded or double-encoded tags
  fixHtmlEncodings = (string) ->
    string = string.replace(/\&amp;#/mg, '&#') # The rest
    string = string.replace(/\&quot;/mg, '"')
    string = string.replace(/\&quote;/mg, '"')
    string = string.replace(/\&#95;/mg, '_')
    string = string.replace(/\&#39;/mg, "'")
    string = string.replace(/\&#34;/mg, '"')
    string = string.replace(/\&#62;/mg, '>')
    string = string.replace(/\&#60;/mg, '<')
    string
  # Run it
  str = fixHtmlEncodings(this)
  decodeHTMLEntities(str)
  
# Test your string here
text = "M<br>d"


$("#escaped").text text
$("#unescaped").text text.unescape()