0

Possible Duplicate:
Javascript code to parse CSV data
Javascript: Splitting a string by comma but ignoring commas in quotes

I have a comma separated string like this:

car,jeep,,"ute,van",suv,truck

I need to split it and add it to array as following entries:

car
jeep

ute,van
suv 
truck

I am currently first splitting the string by " and then replace , with some other character in the parts that have , only in the middle but not at the either ends.

Also I check if the length of split array is greater than 1 because in case I get strings that don't have " at all, I want to skip the replacing , part.

Then finally I join the array using "" to get the end result.

Can someone suggest any better way and efficient way to do this possibly using regex?

Community
  • 1
  • 1
Chaitanya MSV
  • 6,706
  • 12
  • 40
  • 46
  • 1
    You should use a [CSV parser](http://stackoverflow.com/questions/1293147/javascript-code-to-parse-csv-data). – Tim Pietzcker Feb 01 '13 at 10:36
  • 1
    @ChaitanyaM: Uh, that *is* pure JavaScript. – Tim Pietzcker Feb 01 '13 at 10:38
  • Thanks @TimPietzcker for pointing me to CSV Parser. The algorithm there looks like an overkill and hard to understand. I believe my algorithm is simple and easy to understand. So unless proven otherwise, I will stick to mine. – Chaitanya MSV Feb 01 '13 at 10:55
  • No problem to prove otherwise. CSV *is* a nontrivial format. Try this string: `',wood,"2"" by 4""","oak\ncomposite",'`. Your approach fails on escaped quotes and on empty field at the start and end of the string. – Tim Pietzcker Feb 01 '13 at 10:58
  • I can never have empty string at the start. I skip the parts that have , at the either or both ends. So having empty string at the end doesn't harm I believe. Also I missed one more step in my algo. I finally split the string by comma after replacing interim commas with say ; – Chaitanya MSV Feb 01 '13 at 11:10
  • Hey, it's your foot. You choose the gun :) – Tim Pietzcker Feb 01 '13 at 11:12

0 Answers0