Unescape HTML using JavaScript


JavaScript utility function to unescape HTML using regular expression. Given function is fully functional with all checks.

<script type="text/javascript">
function makeString(object) {
      if (object == null) return \'\';
      return String(object);
    };

    var escapeChars = { lt: \'<\',
              gt: \'>\', quot: \'"\', amp: \'&\', apos: "\'"
            };
    
    function unescapeHTML(str) {
          return makeString(str).replace(/&([^;]+);/g, function(entity, entityCode) {
            var match;

            if (entityCode in escapeChars) {
              return escapeChars[entityCode];
            } else if (match = entityCode.match(/^#x([da-fA-F]+)$/)) {
              return String.fromCharCode(parseInt(match[1], 16));
            } else if (match = entityCode.match(/^#(d+)$/)) {
              return String.fromCharCode(~~match[1]);
            } else {
              return entity;
            }
          });
        };
    //test function
    alert(unescapeHTML(\'<p>&lt;&lt;&lt;&gt;&gt;&gt;&gt;&gt;</p>\'));
        
</script>

Below is output

js example