Using a regex lookahead after spaces

12 hours ago 1
ARTICLE AD BOX

I am trying to write a simple script to process JSON5 — the idea is to convert to standard JSON and let JSON.parse() do the rest. I’m using regular expressions to do the conversion.

One part is to handled unquoted keys. In this case, I surround unquoted keys with double quotes. Here is a snippet with a sample:

var sample = ` unquoted: "this is the first", "quoted": "this is the second" `; var result = sample.replaceAll(/^\s*(?!")(.*?):/gm, '[$1]'); console.log(result); // Result: // [unquoted] "this is the first", // [ "quoted"] "this is the second"

I know it’s unfinished, because it hasn’t got the test for the second double quote. In the snippet I use square brackets instead if double quotes to track what’s happening.

I think I need to use a negative lookahead to locate the unquoted key.

The thing is, the negative lookahead appears to conflict with the preceding \s* term. The regex correctly identifies the first unquoted key, but thinks the space before second quoted key is part of the expression. If I change the term to \s\s then it works, but (a) I can’t be sure how much space is at the beginning of each line, and (b) it misinterprets the unquoted key.

What is the trick to using negative lookahead after spaces?

Read Entire Article