Reputation: 35
id like to decode all HTML Entities from a String (named descr, coming from a MySQL-DB)
I use this function to do this:
function htmlDecode(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
And this works fine, if i print the value to a div.
document.getElementById('ABC').innerHTML = htmlDecode(descr); -> Descr = "&" -> Output in Div "&"
But if i print the value to a textarea its not decoded:
document.getElementById('ABCD').value = htmlDecode(descr); -> Descr = "&" -> Output in Textarea "&"
I spend ours in SO, but didtn find a solution. Can you help me?
Upvotes: 1
Views: 2385
Reputation: 11623
You need to a use DOMParser as referenced here.
//this function does the unescaping
function htmlDecode(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
var str="Stars & Stripes"; //arbitrary escaped string
//render the escaped string into the div as-is
document.getElementById("printhere_div").innerHTML = str;
//set the textarea value using the unescaped string
document.getElementById("printhere_textarea").value = htmlDecode(str);
<div id="printhere_div">target div</div>
<textarea id="printhere_textarea">target textarea</textarea>
Upvotes: 2