If I have a string formatted like this:
"name", "bob", "number", 16, "place", "somewhere"
And I want, instead, to have a string like this:
"name": "bob", "number": 16, "place": "somewhere"
Also, the test cases do have some examples of strings like this:
"name", "bob", "hello, world", true
That would need to be formatted like this:
"name" : "bob", "hello, world" : true
...with every odd comma being replaced by a colon (so long as that comma falls outside of quotes), how on Earth would I do that via regex?
I've found the following regex via Google: /(,)(?=(?:[^"]|"[^"]*")*$)/,':'
, which matches the first comma instance. How do I alternate every other one from there on out?
Edit for more info:
What I'm trying to do is take this string where each value is delineated by a comma and format it like a JS object using .replace()
. So, in this case, "name", "number" and "place" represent key values. They're not fixed, this is simply an example.
Regex:
,(.*?(?:,|$))
Replacement string:
:$1
DEMO
Example:
> '"name", "bob", "number", 16, "place", "somewhere" '.replace(/,(.*?(?:,|$))/g, ':$1');
'"name": "bob", "number": 16, "place": "somewhere" '
Update:
If the field names are comma seperated then you could try the below regex,
> '"name", "bob", "hello, world", true'.replace(/("(?:\S+?|\S+ \S+)"), ("[^"]*"|\S+)/g, '$1: $2');
'"name": "bob", "hello, world": true'
You can go with this Regular Expression that covers all matches together.
(?=(?:[^"]*"[^"]*")*[^"]*$)(,)(.*?,|)(?=.*?(?:,|$))
Replacement is: :$2
Live demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With