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?

5
  • 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? Commented Oct 7, 2020 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 & Commented Oct 7, 2020 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 Commented Oct 7, 2020 at 15:54
  • I assume your MySQL database already has the escaped values. Is that a correct assumption? Commented Oct 7, 2020 at 15:56
  • Yes. The DB contains the value & Commented Oct 7, 2020 at 16:02

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.