Grow your CSS skills. Land your dream job.

Last updated on:

Unescape HTML in JS

function htmlDecode(input){
  var e = document.createElement('div');
  e.innerHTML = input;
  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}

Usage

htmlDecode("<img src='myimage.jpg'>"); 
// returns "<img src='myimage.jpg'>"

Comments

  1. mutter
    Permalink to comment#

    Nice. How about the other way around?

  2. kayan
    Permalink to comment#

    This reverses it:

    
      function htmlEncode( input ) {
          return String(input)
              .replace(/&/g, '&')
              .replace(/"/g, '"')
              .replace(/'/g, ''')
              .replace(//g, '>');
    }
    
    • Maybe this is what you mean:

      function htmlEncode( input ) {
          return String(input)
              .replace(/&/g, '&amp;')
              .replace(/"/g, '&quot;')
              .replace(/'/g, ''')
              .replace(/</g, '&lt;')
              .replace(/>/g, '&gt;');
      }
  3. Permalink to comment#

    Nice. How about the other way around?

  4. Permalink to comment#

    But, wouldn’t this execute script tags in the html we are trying to unescape? We wouldn’t want that…

Leave a Comment

Current day month ye@r *

*May or may not contain any actual "CSS" or "Tricks".