Detail refer to http://andrewu.co.uk/clj/entityencode. 
 
 
 
 
 
  Function   Texttoentities (strplaintext, blnpartialencodeonly)      {
  VaR  Strpartial  =  [];
  VaR Strfull  =  [];
  VaR  INTP  =     0  ;
  VaR  INTF  =     0 ;
  VaR  Objpartialregexp  =  (  New  Regexp). Compile (  "  [\ W \ s]  "  );
  For  (  VaR  Inti  = 0  ; Inti  <  Strplaintext. length;  ++  INTI)    {
  VaR  Strchar  = Strplaintext. charat (INTI );
  VaR  Intchar  =  Strchar. charcodeat (  0  );
  If  (Isnan (intchar ))   {
//If char failed to decode, leave as char
Strpartial. Push (strfull. Push (strchar ));
}  
  Else      {
  VaR  Strentity  =     "  &#  "     +  Intchar  +    "  ;  "  ;
Strfull. Push (strentity );
  //  If char was [a-zA-Z0-9 _ \ t] Leave as char, else Replace with Entity  
  Strpartial. Push (objpartialregexp. Test (strchar)  ? Strchar: strentity );
}  
}  
  Return  (Blnpartialencodeonly  ?  Strpartial. Join (  ""  ): Strfull. Join (  ""  ));
}   
   Function  Entitiestotext (strencodedtext)      {
  VaR  Strdata  =  String (strencodedtext );
  VaR  Objregexp  =  ( New  Regexp). Compile (  "  & # (\ D + );  "  ,  "  IG  "  );
  /**/ /*For each match to any entity, replace that
Entity globally with its single char equivalent*/  
  While  (Strdata. Match (objregexp ))    {
  VaR Strcharmatch  =  Regexp. $  1  ;
  VaR  Objregexpmatch  =     New  Regexp (  "  &#  "     + Strcharmatch  +     "  ;  "  ,  "  IG  "  );
Strdata  =  Strdata. Replace (objregexpmatch, String. fromcharcode (strcharmatch ));
}  
 Return  Strdata;
}