Escaping and unescaping a string with single and double quotes in Javascript

Posted by Reina on Stack Overflow See other posts from Stack Overflow or by Reina
Published on 2012-10-25T22:55:58Z Indexed on 2012/10/25 23:00 UTC
Read the original article Hit count: 205

I have a search box that a user can search for any string including single AND double quotes, once they have searched, the backend is passing the keyword back to me so I can put it back in the box. I don't know what the string is so I can't escape quotes myself, below is an example:

var keyword = "hello";
$("#selectionkeywords").val();

The issue I am having is that if the user enters "hello" the keyword becomes ""hello"" and I get this error:

missing ) after argument list
[Break On This Error]   
jQuery("#selectionkeywords").val(""hello"");

The user could also enter single quotes so that rules it out as well. I tried using escape unescape but I still have the same issue e.g. escape(""hello"") I could get the value in an unescaped format e.g. "hello" but I don't know what to do with it, escape doesn't work on it I end up with this %26%23034%3Bhello%26%23034%3B

So I'm pretty much stuck at the moment as I can't do anything to the string, any ideas?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery