Escaping Single and Double Quotes in a generated String

Hi,
I’ve been wrestling with this issue for a while and I’m hoping someone can help.

I am building an administrative panel for one of my applications using ajax so I’m using lots of javascript to display information on the page. I’m having an issue with one piece in particular. Depending on the quoting system I use I cannot properly display strings with quotes in them

Here is the code:

text +="<td><input type=\\"text\\" name=\\"image_"+calendar.images[i].key+"\\" value=\\""+calendar.images[i].caption+"\\" size=\\"50\\" maxlength=\\'250\\'></td>";

if my value in the field calendar.images[i].caption has double quotes (") around the text or part of the text, that section of the text does not display. However single quotes display for example if the text was i’m “ready for a ride” only i’m shows up (it thinks the part in quotes is a parameter). I have tried switching all of my escaped " to ’ and then I can display the part in double quotes but not the part with a single quote.

Is there a method (other than escape() - I tried that it changes the spaces and quotes to %characters so that won’t work for display and editing purposes) for automatically taking a string and processing it to add in the escape character(\) before '(single) or "(double) quotes in the string?
I’m not good at regular expressions is there a way to do it with the string.replace() method or does the language already provide a function for this?

Thanks in advance for you help!
Mac

string.replace(/‘\/g,"\\’") will escape all apostrophes in the string

string.replace(/\“/g,'\\”') will escape all quotes.

You could probably do both at once (just off the top of my head and not tested)

string.replace(/([\"\‘])/g,’\\'+$1)