Wednesday, March 6, 2013

Javascript to convert HTML entity code to Original Character and viceversa

 
The following javascript functions will be useful when working with special characters in HTML.
 
First function converts html entities to literal characters, second function does the reverse

// This Fucntion will decode an entity to its original character
// eg & will become '&' and '"' will become "
function entityToText(entityText) {
      var d = document.createElement("div");
      d.innerHTML = entityText;
      return d.firstChild.nodeValue;
}
 
// This Fucntion will encode a special character to its entity
// eg ‘&’ will become '&' and " will become '"'
function textToEntity(specialText) {
     var d = document.createElement("div");
     d.appendChild(document.createTextNode(specialText));
     return d.innerHTML;
}
 
 
alert(entityToText('&lt;&gt;&amp;&quot;')); // returns <>&"
alert(textToEntity('<&>')); // returns &lt;&amp;&gt;
 
 
.

No comments:

Post a Comment