28 April, 2017

CSV to Array converter for Inverted comma(") data using Java Script

Let's see we have CSV data with comma delimited like
 a,b,"c,d","e,f" and we need output c,d in array output index 2. we need simply this function:-

function CSVtoArray(str)
    //split the str first 
    //then merge the elments between two double quotes 
    var delimiter = ','; 
    var quotes = '"'; 
    var elements = str.split(delimiter); 
    var tmp="";
    var newElements = []; 
    var indexOfRightQuotes = 0;
   
    for (var i = 0; i < elements.length; ++i)
    {
           //found the left double quotes 
            if (indexOfRightQuotes==0)
        {
                    if (elements[i].indexOf(quotes) >= 0)
                  {//the left double quotes is found 
                    var indexOfRightQuotes = -1; 
                    tmp = elements[i].replace('"',''); 
                } 
              else
              {
                  newElements.push(elements[i]);
              }
         }
            //found the right double quotes 
            //merge all the elements between double quotes 
        else if (indexOfRightQuotes==-1)
        {
                    if (elements[i].indexOf(quotes) >= 0)
                {
                    indexOfRightQuotes=0;
                  tmp = tmp + delimiter + elements[i].replace('"',''); 
                  newElements.push(tmp);
                  tmp="";
                }
                else
                {
                       tmp = tmp + delimiter + elements[i].replace('"',''); 
                }
          }       
    } 

    return newElements; 
}
var abc=CSVtoArray('a,b,"c,d","e,f"');  // call function with data
document.write(abc[2]);  //print  c,d