Converting character entity codes into characters using JavaScript


J

Jimbo

Basically I'm looking for a function that will parse a string and
replace any entity codes it finds w/ the actual character.

For instance the function would convert "Hello World" into "Hello
World"

Has anyone ever heard of a function that can do that?

Thanks!
 
Ad

Advertisements

M

Martin Honnen

Jimbo said:
Basically I'm looking for a function that will parse a string and
replace any entity codes it finds w/ the actual character.

For instance the function would convert "Hello World" into "Hello
World"

A HTML parser can do that so doing e.g.
var div = document.createElement('div');
div.innerHTML = "Hello World";
and then reading out the text content of the div element should do:

function htmlToText (htmlMarkup) {
var div = document.createElement('div');
div.innerHTML = htmlMarkup;
if (typeof div.innerText != 'undefined')
{
return div.innerText;
}
else if (typeof div.ownerDocument != 'undefined' &&
typeof div.ownerDocument.createRange != 'undefined')
{
var range = div.ownerDocument.createRange();
range.selectNodeContents(div);
return range.toString();
}
else if (typeof div.textContent != 'undefined')
{
return div.textContent;
}
}

var text = htmlToText("Hello World");


You might want to add some object detection to prevent errors in older
browsers like Netscape 4 or IE 4.
 

Top