views:

249

answers:

2

Sample Conversions

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

Any small library function that can handle this?

+5  A: 

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;
}
CMS
@CMS: please see my comment to bboe
Michael
@Michael: Give a look to my edit...
CMS
A: 

Looks like this will do:

function html_entity_decode(s) {
  var t=document.createElement('textarea');
  t.innerHTML = s;
  var v = t.value;
  t.parentNode.removeChild(t);
  return v;
}

Source

bboe
I have no document object and this should not rely on it, since I'm using JSM XUL.
Michael
You can use the code (http://phpjs.org/functions/htmlentities:425) which relies on a table lookup. You need to reverse the lookup to decode the entities.
bboe