Javascript replacing HTML char code with actual character

你。 提交于 2020-01-11 09:50:13

问题


I have a HTML input text, and its values are populated from a related div. My problem is that the div contains characters like & which will display correcly as '&' sign in div but when copied to text box the text '&' will be dispalyed

How can i convert &amp; to & and '&lt;' to '<', '&nbsp;' to ' ' ???


回答1:


You thus want to unescape HTML entities. With plain JS you can use this snippet:

function unescapeHTML(html) {
    var div = document.createElement("DIV");
    div.innerHTML = html;
    return ("innerText" in div) ? div.innerText : div.textContent; // IE | FF
}

And with jQuery the following one:

function unescapeHTML(html) {
    return $("<div />").html(html).text();
}

But you can also just fix this problem during the step that you "copy" the div's content into the input element's value. Instead of grabbing HTML, just grab text. Instead of element.innerHTML, that'll be element.innerText for IE or element.textContent for real browsers.

No, you can't and shouldn't do this (reliably) with regex.




回答2:


I am not sure how you are accessing data but a possible solution could be use of innerText property instead on innerHtml



来源:https://stackoverflow.com/questions/2989039/javascript-replacing-html-char-code-with-actual-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!