Vlad
Vlad

Reputation: 1919

Javascript Regex - negative lookbehind and lookahead

I'm trying to parse data into JSON. The data looks like this:

[{ 
    'Id': 1,
    'FirstName': 'bob',
    'LastName': '',
    'Description': 'description can include escaped single quotes: \'.' 
}]

How the result should be:

[{ 
    "Id": 1,
    "FirstName": "bob",
    "LastName": "",
    "Description": "description can include escaped single quotes: \'."
}]

The point is to replace all unescaped single quotes with double quotes while leaving escaped quotes alone.

I have regex which already works well in converting single quotes into double quotes for JSON while ignoring the escaped single quotes.

/((?!\\).{1}|^.{0,0})\'/g

Problem: The problem is that for the bit 'LastName': '', it only replaces the first quote with a " and not the second... making it into this: "LastName": "' which is invalid JSON.

Question: How can I modify my regex to make sure both single quotes get replaced? I feel like running string.replace twice in a row is a dirty solution...

Upvotes: 2

Views: 264

Answers (2)

alpeshpandya
alpeshpandya

Reputation: 492

I think storing your data in JavaScript variable and using JSON.stringify will be best way of achieving what you are trying to do. It will take care of escaping special characters for you and you don't have to keep maintaining your Regex to handle more scenarios.

obj=[{  'Id': 1,  'FirstName': 'bob', 'LastName': '', 'Description': 'description can include escaped single quotes: \'.'}]
str=JSON.stringify(obj)

After this your str will have this value: [{"Id":1,"FirstName":"bob","LastName":"","Description":"description can include escaped single quotes: '."}]

Upvotes: 2

revo
revo

Reputation: 48711

Lookbehind is not supported by javascript. You can't do it with a positive lookahead either. There is a more reliable way to do this without thinking about lookarounds at all:

var str = str = `[{ 
    'Id': '',
    'FirstName': 'bo\\\\\\\\'b',
    'LastName': '',
    'Description': 'des\\\\\\'cription can\\\\' include \\\\\\\\'escaped\\'single quotes: \\'.' 
}]`;

console.log(str.replace(/(\\\\)+(')|\\+'|(')/g, function(match, p1, p2, p3) {
    return p2 ? p1 + '\\"' : (p3 ? '"' : match);
}));

Upvotes: 1

Related Questions