Skip to content

JavaScript convert HTML entities | Example code

  • by

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

Do comment if you have any doubts or suggestions on this topic.

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

Your email address will not be published. Required fields are marked *