3

I'm looking to split a string that is comma separated. The array1 is populated from a string of rows got in a .csv file.

Array2 then splits this into seperate values. It works fine, but not if I have a comma inside quotes.

for (var i = 0; i < array1.length; i++) {
    array2.push(array1[i].split(","));      
}

i.e.

array1[0] = abcde, defg, hijkl;
array1[1] = abcde, "def,ghi" , jklmn;

should become

array2[0]....
array2[1][0] = abcde
array2[1][1] = def,ghi
array2[1][2] = jklmn

How can I prevent a split at the quoted comma?

Laurent
  • 3,798
  • 25
  • 22
Patrick Keane
  • 663
  • 3
  • 19
  • 41
  • 3
    You'll have to write a full-blown CSV parser. You can't blindly apply a regex to csv and hope to get good results. – Marc B Oct 08 '13 at 15:08
  • 4
    CSV parsing is a common task. I would use a third-party library that has the edge cases handled and move on. – Jason P Oct 08 '13 at 15:13
  • 1
    See [this answer](http://stackoverflow.com/questions/1293147/javascript-code-to-parse-csv-data) – J David Smith Oct 08 '13 at 18:57

1 Answers1

0

Use a look ahead in your regex:

split(",(?=(([^\"]*\"){2})*[^\"]*$)")

This splits only on commas followed by an even number of quotes (those followed by an odd number must be within quotes).

Bohemian
  • 412,405
  • 93
  • 575
  • 722