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!
 
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,906
Latest member
SkinfixSkintag

Latest Threads

Top