JavaScript convert HTML entities | Example code

Decoding HTML characters by using a DOM element assign value. Using textarea specifically so that the tags are preserved but HTML entities still get decoded.

Decode a string that has special HTML entities Example

HTML example code.

<!DOCTYPE html>
<html>
<body>
  <form id="form">
    <input type="text" id="input" value="Entity:&amp;nbsp; Bad attempt at XSS:<script>alert('new\nline?')</script><br>">
    <input type="submit" value="Show">
  </form>

  <script>
   function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
  }

  document.getElementById('form').onsubmit = function(e) {
    e.preventDefault();
    var input = document.getElementById('input').value;
    var output = decodeHtml(input);
    alert(output);
  }
</script>
</body>
</html>

Output:

JavaScript convert HTML entities

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.