Skip to content Skip to sidebar Skip to footer

Javascript Replacing Html Char Code With Actual Character

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

Solution 1:

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

functionunescapeHTML(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:

functionunescapeHTML(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.

Solution 2:

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

Post a Comment for "Javascript Replacing Html Char Code With Actual Character"