views:

231

answers:

2

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  A: 

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

Ramesh Soni
+3  A: 

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.

BalusC
Note that `unescape` and `escape` are already functions in Javascript and using this code will override those functions. They are deprecated functions however, so it probably doesn't matter that much. Also, if an empty string were passed to the Plain Ol' JS(tm) method, "undefined" would be returned in IE, because you're using a "falsey" condition check. `"innerText" in div ? div.innerText : div.textContent;` would fix this.
Andy E
@Andy: It was just a kickoff example, but that are fair points. I've fixed as per your comments.
BalusC