I would like to replace all commas in a comma-delimited string with a pipe ('|') except for those that are found in double quotes. I would prefer to use the JavaScript "replace" function if possible.
My regex knowledge is limited at best. I am able to replace all commas with pipes, but that does not give me the desired result for parsing through the data. I also found a regex on here that removed all commas except those in quotations, but does not implement a pipe or some other delimiter.
(?!\B"[^"]*),(?![^"]*"\B)
Here is an example of what I'm trying to accomplish:
string1 = 1234,Cake,,"Smith,John",,"Status: Acknowledge,Accept",,Red,,
and I would like it to look like:
string1 = 1234|Cake||"Smith,John"||"Status: Ackknowledge,Accept"||Red||
One option is to use a replace callback to replace either a quote or a comma with the quote itself or a pipe respectively:
str = `1234,Cake,,"Smith,John",,"Status: Acknowledge,Accept",,Red,,`;
res = str.replace(/(".*?")|,/g, (...m) => m[1] || '|');
console.log(res)
Another (and IMO better in the long run) would be to use a dedicated parser to work with CSV data. CSV is actually trickier than it looks.
We can simply capture our desired commas using alternation with a simple expression such as:
(".+?")|(,)
jex.im visualizes regular expressions:

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