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

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like ```this```. You don't need to escape code in backticks, Markdown does that for you.

Sadly, it's kind of broken. WordPress only accepts a subset of HTML in comments, which makes sense, because certainly some HTML can't be allowed, like <script> tags. But this stripping happens before the comment is processed by Markdown (via Jetpack). It seems to me that would be reversed, because after Markdown processes code in backticks, it's escaped, thus safe. If you think you can fix this issue, get in touch!

If you need to make sure the code (typically HTML) you post absolutely posts correctly, escape it and put it within <pre><code> tags.

Current ye@r *

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