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:&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:
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