最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regular expression to escape double quotes within double quotes - Stack Overflow

programmeradmin2浏览0评论

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 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.

Share Improve this question edited May 15, 2013 at 14:47 Yurii Dolhikh asked May 15, 2013 at 14:37 Yurii DolhikhYurii Dolhikh 691 gold badge1 silver badge7 bronze badges 6
  • 2 You need to fix the problem at whatever is generating the JSON. – Explosion Pills Commented May 15, 2013 at 14:40
  • How do you know where is opening and closing " – anubhava Commented May 15, 2013 at 14:44
  • First and last before/after the ':'. – Yurii Dolhikh Commented May 15, 2013 at 14:46
  • I concur with @ExplosionPills, you need to use code that already knows how to build JSON if you can...those quotes should be escaped BEFORE you get the JSON string...otherwise, you're going to need some plex look-ahead/look-behind expressions that will likely get nasty. I'm better than most people with regexes (not an expert by any means) and I wouldn't want to figure this out. – Kevin Nelson Commented May 15, 2013 at 14:52
  • e.g. what if your JSON does: "id_clients":""588","44"", how does it know to ignore the ", after 588 because it looks like JSON. – Kevin Nelson Commented May 15, 2013 at 14:54
 |  Show 1 more ment

2 Answers 2

Reset to default 5

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

You can try, although this will work only for the opening tags :

.replace(/\"\"/g, '\\""');
发布评论

评论列表(0)

  1. 暂无评论