Javascript replace HTML char code with actual character

I have HTML input text and its values ​​are populated from the associated div. My problem is that the div contains characters of the type &that will be displayed as a character '&'in the div, but when copying to the text field, the text will be displayed'&'

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

+3
source share
2 answers

So you want unescape HTML objects . With simple 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:

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

, "" div . , HTML, . element.innerHTML element.innerText IE element.textContent .

, () .

+5

, , innerText innerHtml

+1

Source: https://habr.com/ru/post/1748830/


All Articles