[RESOLVED] convert HTML Entities into normal characters
I'm using javascript to display some parts of the source-code from a webpage. This occasionaly contains HTML entities (& instead of &, é instead of é, etc.) I want to convert these entities (&, é) back into normal characters (&, é). Of course i can do this with String.replace(), but the list of entities is kinda long, so i was hoping there is a simpler way that i'm unaware of.
Anyone got any ideas?
Put the text as is in an empty html element's innerHTML, then read the data value. No need to attach the element to the document tree.
function get_ents(str){
var temp=document.createElement("pre");
temp.innerHTML=str;
return temp.firstChild.nodeValue;
}
var str='Tom & Jerry';
get_ents(str) returns 'Tom & Jerry'.
He's looking for a JavaScript equivalent of PHP's html_entity_decode function.
A first attempt but it seems to work fine in both Firefox and IE.
Code:
<script type="text/javascript">
function html_entity_decode(str){
/*Firefox (and IE if the string contains no elements surrounded by angle brackets )*/
try{
var ta=document.createElement("textarea");
ta.innerHTML=str;
return ta.value;
}catch(e){};
/*Internet Explorer*/
try{
var d=document.createElement("div");
d.innerHTML=str.replace(/</g,"<").replace(/>/g,">");
if(typeof d.innerText!="undefined")return d.innerText;/*Sadly this strips tags as well*/
}catch(e){}
}
</script>
<script type="text/javascript">
alert( html_entity_decode("<span>¿Hablas bien el español?</span>") );
</script>
<script type="text/javascript">
function html_entity_decode(str){
/*Firefox (and IE if the string contains no elements surrounded by angle brackets )*/
try{
var ta=document.createElement("textarea");
ta.innerHTML=str;
return ta.value;
}catch(e){};
/*Internet Explorer*/
try{
var d=document.createElement("div");
d.innerHTML=str.replace(/</g,"<").replace(/>/g,">");
if(typeof d.innerText!="undefined")return d.innerText;/*Sadly this strips tags as well*/
}catch(e){}
}
</script>
<script type="text/javascript">
alert( html_entity_decode("<span>¿Hablas bien el español?</span>") );
</script>
Pretty sloppy but it should open up some new ideas.
Yea, it definitely does!
that DOMParser object does the trick. In the end i only had to copy & paste just that function to my javascript file and it works like a charm.
Many thanks for this brilliant idea!
function html_entity_decode(str) {
var ta=document.createElement("textarea");
ta.innerHTML=str.replace(/</g,"<").replace(/>/g,">");
return ta.value;
}
Bookmarks