Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to escape double quotes within double quotes

I have a string that needs to be parsed as JSON.

The problem is, it may sometimes contain double quotes, causing errors in parsing.

For example:

{
    "id_clients":"58844",

    "id_clients_name" : ""100" test"qw"
}

I need a regex to replace any double quotes between the opening and closing " with a \".

Thanks.

like image 567
Yurii Dolhikh Avatar asked Oct 26 '25 22:10

Yurii Dolhikh


1 Answers

I tried it just for fun, even though it is certainly better to fix the generator. This might work in your case, or at least inspire you:

You can try it here

$( function() 
{
  var myString = "{ \"na\"\"me\": \"va\"lue\", \"tes\"\"t\":\"ok\" }";
  var myRegexp = /\s*\"([\w\"]+)\"\s*[,}:]/g;
  var match;
  var matches = [];

  // Save all the matches
  while((match = myRegexp.exec(myString)) !== null)
  {
      matches.push(match[1]);
      console.log(match[1]);
  }

  // Process them
  var newString = myString;
  for (var i=0; i<matches.length; i++)
  {
      var newVal = matches[i].replace(/\"/g, '\\\"'); 
      newString = newString.replace(matches[i], newVal);
  }
  alert(myString + "\n" + newString);
}
);
like image 139
JonasVautherin Avatar answered Oct 29 '25 12:10

JonasVautherin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!