Reputation:
I'm trying to store values from a database into HTML5 data
attributes.
I can escape them fine because of this answer, but how do I reverse that?
Upvotes: 1
Views: 11458
Reputation: 10407
To handle all potential characters (instead of a "known" list), use the natural escaping of the browser by letting it convert HTML strings to text with this:
function unescapeHTML(string) {
var elt = document.createElement("span");
elt.innerHTML = string;
return elt.innerText;
}
References:
document.createElement
- https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement*.innerHTML
- https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML*.innerText
- https://developer.mozilla.org/en-US/docs/Web/API/Node/innerTextUpvotes: 8
Reputation: 50905
Just reverse the function:
function unescapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, "\"")
.replace(/'/g, "'");
}
DEMO: http://jsfiddle.net/wazXb/
Upvotes: 9