Anatoliy Gatt
Anatoliy Gatt

Reputation: 2491

Escape double quotes within double quotes with Regex[JS]

I have a JSON string: '{"place": {"address": "Main Street, \"The House\""}}'.

Before parsing it with JSON.parse() I have to make sure that the double quotes within double quotes are escaped properly.

I was trying to come up with the regex that would match "The House", but failed to so.

Any idea on how can I achieve desired result?

Upvotes: 0

Views: 2827

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174844

This would be possible with the help of positive lookahead assertion.

var s = '{"place": {"address": "Main Street, "The House""}}';
alert(s.replace(/"((?:"[^"]*"|[^"])*?)"(?=[:}])/g, function(m,group)
                          {
                            return '"' + group.replace(/"/g, '\\"') + '"'
                          }))

OR

var s = '{"place": {"address": "Main Street, "The House"", "country": "United Kingdom"}}';
alert(s.replace(/"((?:"[^"]*"|[^"])*?)"(?=[:},])(?=(?:"[^"]*"|[^"])*$)/gm, function(m,group)
                          {
                            return '"' + group.replace(/"/g, '\\"') + '"'
                          }))

Upvotes: 3

Related Questions