4

I am getting data from text box and change it into xml format and store it in data base. For allowing special characters i wrote javascript function to replace special character with its html entities.

 "     "
 &     &
 <     &lt;
 >     &gt;

for "quotes , less than , greater than" its working fine. for "&" it is showing xml parser error i used javascript to replace special character with its entity

  string.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, "\\'");

  for "&" allow showing warning but it get stored in data base. please help me to sort out this problem . 


 i begin with string.replace(/&/g, '&amp;') even though i am getting 

Warning: SimpleXMLElement::__construct(): Entity: line 9: parser error : EntityRef: expecting ';' in /var/www/ i tried this also &amp;amp; as mentioned in this link stackoverflow.com/questions/1328538/…
After that there is no warning but while saving in db it saved as "ab &amp cd"

Community
  • 1
  • 1
suganya
  • 235
  • 2
  • 4
  • 12
  • 1
    Once you write parse error, once warning - what's the case now? Can you post the error/warning-message please? – Christoph Jul 19 '12 at 07:37
  • What database? Where is the JS running (browser? node? soething else?)? Is the JS talking directly to the database or do you have some server side program in between? – Quentin Jul 19 '12 at 08:09

1 Answers1

6

Start with replacing the & character, then replace the other characters. Otherwise you will replace & from the previous entities (&lt; etc.) by &amp;

string.replace(/&/g, '&amp;amp;') //<= start with
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&apos');
// &apos; may be "\\'",  depends on how te OP wants to use it

[edit based on comments] use &amp;amp; to replace the ampersand character

KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • thanks for yr reply. i started with string.replace(/&/g, '&') even though i am getting Warning: SimpleXMLElement::__construct(): Entity: line 9: parser error : xmlParseEntityRef: no name in /var/www/... i tried this also &amp as mentioned in this link http://stackoverflow.com/questions/1328538/how-do-i-escape-ampersands-in-xml there is no warning but while saving in db it saved as "ab &amp cd" . – suganya Jul 19 '12 at 08:56
  • Would `&amp;` (semicolon added) instead of `&amp` work? – KooiInc Jul 19 '12 at 09:50
  • thanks Yaar. Even though i am getting same warning :( and while saving in DB it is saving as "ab &amp cd" instead of "ab & cd" . :( no idea to proceed. – suganya Jul 19 '12 at 10:32
  • even i use string.replace(/&/g, '&') instead of "&" it is get saved in database but i am getting ***Warning: SimpleXMLElement::__construct(): Entity: line 9: parser error : xmlParseEntityRef: no name in /var/www/** – suganya Jul 19 '12 at 11:00