Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

marked as duplicate by Felix Kling, Tim Pietzcker, Yoshi, Christoph, raina77ow Feb 1 '13 at 10:43

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
You should use a CSV parser. –  Tim Pietzcker Feb 1 '13 at 10:36
1  
@ChaitanyaM: Uh, that is pure JavaScript. –  Tim Pietzcker Feb 1 '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. –  Chaitanyamsv Feb 1 '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 1 '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 ; –  Chaitanyamsv Feb 1 '13 at 11:10

Browse other questions tagged or ask your own question.