Search code examples
javascriptjqueryhtml-encode

vanilla js alternative to jquery method to perform safe html decode?


I've got a single dependency on jQuery that I don't want, and need a browser-safe method to decode server-side html encoded content.

The effect I'm going for is to replace an existing DOM element with the the html that gets decoded, along the following lines:

$('#targetId').replaceWith($('<div/>').html(value).text());

where value contains an html-encoded string.

Alternatively, an more direct approach would also be welcome.


Solution

  • Here's one way to do it:

    function DecodeHtmlString(htmlString){
      var temp = document.createElement("textarea");
      temp.innerHTML = htmlString;
      return temp.value;
    }