简体   繁体   中英

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.

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);
}
);

您可以尝试,虽然这只适用于开始标记:

.replace(/\"\"/g, '\\""');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM