Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
161
rated 0 times [  165] [ 4]  / answers: 1 / hits: 17867  / 14 Years ago, tue, may 11, 2010, 12:00:00

Sample conversions:



 & -> `&`
> -> `>`


Any small library function that can handle this?


More From » html

 Answers
6

I have on my utility belt this tiny function always:



function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes[0].nodeValue;
}

htmlDecode(&); // &
htmlDecode(>); // >


It will work for all HTML Entities.



Edit: Since you aren't in a DOM environment, I think you will have to do it by the hard way:



function htmlDecode (input) {
return input.replace(/&/g, &)
.replace(/&lt;/g, <)
.replace(/&gt;/g, >);
//...
}


If you don't like the chained replacements, you could build an object to store your entities, e.g.:



function htmlDecode (input) {
var entities= {
&amp;: &,
&lt;: <,
&gt;: >
//....
};

for (var prop in entities) {
if (entities.hasOwnProperty(prop)) {
input = input.replace(new RegExp(prop, g), entities[prop]);
}
}
return input;
}

[#96819] Friday, May 7, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
carlton

Total Points: 373
Total Questions: 123
Total Answers: 97

Location: Saint Helena
Member since Wed, Nov 9, 2022
2 Years ago
;