Adam Adam - 1 month ago 22
Javascript Question

Single quotes in string with jQuery ajax

I have run into a problem where the user enters data and if there are single quotes at all, the script errors out.

What's the best way to handle single quotes that users enter so it doesn't interfere with the jquery/javascript?

UPDATE:

I'm sending it through ajax to a database. here is the data parameter for a json ajax call.

data: "{str_" + sectionName + " :'" + UpdateText + "',EntityID: '" + EntityID + "' }",


with update text being the string that can contain the quotes.

Answer

You could find one of the many String.replaceAll implementations or write your own, and just replace any single or double quotes with an escaped version like \" or \'.