1

Possible Duplicate:
Javascript code to parse CSV data

i have this string:

"display, Name" <test@test.com>, display" Name <test@test.com>, test@test.com

i want to separate this string into an array

array[0] = "\"display, Name\" <test@test.com>"
array[1] = "display\" Name <test@test.com>"
array[2] = "test@test.com"

here is my code:

var comma = inQuotes = false;
for(var i=0;i<str.length;i++) {
            if (str[i] == '"') inQuotes = !inQuotes;
            comma = (str[i] == "," && !inQuotes)  ? true : false;
            item += (!comma) ? str[i] : "";
            if(comma || i == str.length-1) {  
                items.push(item);
                item = "";
            }    
        } 

my problem is that if you have one double quotes without a closer in a string

i appreciate the help...

Community
  • 1
  • 1
Erana111
  • 11
  • 3
  • Without _some_ form of consistency it's going to be hard. If these followed the email address protocol (`email@address.com`, `name `) this would be a lot easier. Is it guaranteed to be malformed like you're providing? I stray quote (opening without close or close without opening) is going to make this brutally complex. – Brad Christie Nov 09 '12 at 21:40
  • 1
    Related - http://stackoverflow.com/questions/1293147/javascript-code-to-parse-csv-data – Jason McCreary Nov 09 '12 at 21:41
  • @JasonMcCreary: This isn't CSV, it's a list of malformed [RFC2822](http://www.faqs.org/rfcs/rfc2822.html) email addresses. – Brad Christie Nov 09 '12 at 21:43
  • I understand. The solution scales nonetheless. – Jason McCreary Nov 09 '12 at 21:44

1 Answers1

1

I tried this and it working for above string jsfiddle

var a = '"display, Name" <test@test.com>, display" Name <test@test.com>, test@test.com';
var aa = a.match(/"(.*?)"(.*?),|(.*?),|(.*?)$/g); 
aa.pop();
aa // [""display, Name" <test@test.com>,", " display" Name <test@test.com>,", " test@test.com"]
Anoop
  • 23,044
  • 10
  • 62
  • 76
  • +1 for good bid. My other option was to look-behind for something resembling `email@address.com` or a `>`, but javascript doesn't do look-behinds. I guess ungreedy matching is just as good in this case. – Brad Christie Nov 09 '12 at 21:51
  • thanks but its not bullet proof test it: "display, Name" , display" Name , "display, name" – Erana111 Nov 09 '12 at 22:12
  • @Erana111 how should any programmatic solution know, that quotes number 4 and 5 belong together, and not 3 and 4 (with 5 being unmatched) – Martin Ender Nov 09 '12 at 22:28