1

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?

Pascalus
  • 35
  • 4
  • `innerHTML` is placing actual HTML into the element, which is being interpreted by the browser to show cleanly. `value` of a textarea is placing raw text. What happens when you do NOT decode it for the textarea? – Marc Oct 07 '20 at 15:51
  • Sorry, but this is a simple misunderstanding of what HTML is and how the elements work. If you set `&` into a div, it will **render** that to just `&`... if you put it in a textbox (or textarea) it will literally show `&` – freefaller Oct 07 '20 at 15:51
  • Thanks for the answers. Without decoding the textarea-value, it still shows & Do you know any solution, how i can convert the text to the textarea correctly? Normaly i would use PHP, but i need a JS Solution here – Pascalus Oct 07 '20 at 15:54
  • I assume your MySQL database already has the escaped values. Is that a correct assumption? – Marc Oct 07 '20 at 15:56
  • Yes. The DB contains the value & – Pascalus Oct 07 '20 at 16:02

1 Answers1

2

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>
Marc
  • 11,403
  • 2
  • 35
  • 45