Search code examples
javascriptjquerystripslashes

How to strip slashes in Javascript (json)? Any JQuery plugin?


So, when I save the data into database, PHP will add a \ on single or double quotes. That is good.

However, when data is passed back to the client using json_encode(); TEXT like McDonald's is STORED as McDonald's in the DB but once passed back from PHP to js, it will be encoded as McDonald\'s

Since I'm using jQuery, is there any plugin to easily do that? or any function I should use to strip the slashes correctly? obviously, if there is case like \\\\s, the function should return \s. :)

Sorry guys. I think I made my question too complicated. How about I make it simpler..

If I have a javascript variable:

var abc = "McDonald\'s";
var bcd = "I need a slash \\ ";
var cde = "save the double quote \"";

how can I strip the \' ? what the regex I should use?


Solution

  • Use: http://au.php.net/manual/en/function.mysql-real-escape-string.php before storing into database.

    Use a custom function like this before writing onto any user interface:

    function unescape($string)
    {
    
    $search = array("\\x00", "\\n", "\\r", "\\\x1a");
    
    $replace = array("\x00","\n", "\r", "\x1a");
    
    $retString = str_replace($search, $replace, $string);
    
    $search = array("\'", '\\'.'"');
    
    $replace = array(  "'", '"',);
    
    $retString = str_replace($search, $replace, $retString);
    
    $search = array("\\\\");
    
    $replace = array( "\\");
    
    $retString = str_replace($search, $replace, $retString);
    
    return $retString
    
    }