Split a CSV into an array of string in Javascript

/**
* @desc split a row of csv data into a list of strings. 
* @param string csvRowData - a row of csv data
* @return list[string] result
*/
function CSVSplit(csvRowData){
    
    csvRowData = csvRowData.replace("\r", "");
    var data = [];
    var seekMode = false;
    var startPos = 0;
    
    for(var i = 0; i < csvRowData.length; i++) {
        
        var char =  csvRowData[i];
      
        switch(char){
            
            case "\"":
            
                if(i < csvRowData.length - 1) {
                    
                    var charN = csvRowData[i + 1];
                    
                    if(charN == ",") {
                        
                        // if two chars are ", : meaning it's the end of seeking mode
                        seekMode = false;
                        
                        var value = csvRowData.slice(startPos + 1, i);
                        
                        // skip next char
                        i++;
                      
                        // always skip the ,
                        startPos = i + 1;
                        
                        
                        // add value to the list
                        data.push(value);
                      
                        continue;
                        
                    } 
                    
                }
                
                break;
                
            case ",":

                if(!seekMode) {
                  
                  // if not then split the data
                  var value = csvRowData.slice(startPos, i);
                  
                  // always skip the ,
                  startPos = i + 1;
                  
                
                  // add value to the list
                  data.push(value);
                  
                }
            
                // first check whether it is in the range
            
                if(i < csvRowData.length - 1) {
                    
                    var charN = csvRowData[i + 1];
                    
                    if(charN == "\"") {
                        
                        // if two chars are ," : meaning it's the start of seeking mode
                        seekMode = true;
                      

                    }
                }
                

                
                break;
            
        }
        
    }
    
    // after done looping, wrap it up, add the last value
    var value = csvRowData.slice(startPos, csvRowData.length);
    
    data.push(value);
    
    return data;
    
}

 

Example usage:

string -> array[string]


Tagged: ,

Leave a comment

Your email address will not be published. Required fields are marked *