Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Replace all commas not in double quotes [duplicate]

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||
like image 556
AC_Slater Avatar asked Jul 10 '26 08:07

AC_Slater


2 Answers

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.

like image 95
georg Avatar answered Jul 13 '26 09:07

georg


We can simply capture our desired commas using alternation with a simple expression such as:

(".+?")|(,)

Demo

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

like image 23
Emma Avatar answered Jul 13 '26 10:07

Emma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!