Regular expression to escape double quotes within double quotes

11,206

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);
}
);
Share:
11,206
Yurii Dolhikh
Author by

Yurii Dolhikh

Updated on June 04, 2022

Comments

  • Yurii Dolhikh
    Yurii Dolhikh almost 2 years

    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.