简体   繁体   English

将 JS 中的 HTML 实体解码为文本框值

[英]Decode HTML Entities in JS to Textbox Value

id like to decode all HTML Entities from a String (named descr, coming from a MySQL-DB) id 喜欢从字符串中解码所有 HTML 实体(名为 descr,来自 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.这工作正常,如果我将值打印到 div。

document.getElementById('ABC').innerHTML = htmlDecode(descr); -> Descr = "&" -> Output in Div "&"

But if i print the value to a textarea its not decoded:但是,如果我将值打印到 textarea 未解码:

document.getElementById('ABCD').value = htmlDecode(descr); -> Descr = "&" -> Output in Textarea "&"

I spend ours in SO, but didtn find a solution.我把我们的花在 SO 上,但没有找到解决方案。 Can you help me?你能帮助我吗?

You need to a use DOMParser as referenced here .您需要使用此处引用的 DOMParser。

 //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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM