1 //Source: http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm
2 // This will parse a delimited string into an array of
3 // arrays. The default delimiter is the comma, but this
4 // can be overriden in the second argument.
5 function csvToArray( strData, strDelimiter ){
6 // Check to see if the delimiter is defined. If not,
7 // then default to comma.
8 strDelimiter = (strDelimiter || ",");
10 // Create a regular expression to parse the CSV values.
11 var objPattern = new RegExp(
14 "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
17 "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
20 "([^\"\\" + strDelimiter + "\\r\\n]*))"
26 // Create an array to hold our data. Give the array
27 // a default empty first row.
30 // Create an array to hold our individual pattern
32 var arrMatches = null;
35 // Keep looping over the regular expression matches
36 // until we can no longer find a match.
37 while (arrMatches = objPattern.exec( strData )){
39 // Get the delimiter that was found.
40 var strMatchedDelimiter = arrMatches[ 1 ];
42 // Check to see if the given delimiter has a length
43 // (is not the start of string) and if it matches
44 // field delimiter. If id does not, then we know
45 // that this delimiter is a row delimiter.
47 strMatchedDelimiter.length &&
48 (strMatchedDelimiter !== strDelimiter)
51 // Since we have reached a new row of data,
52 // add an empty row to our data array.
58 // Now that we have our delimiter out of the way,
59 // let's check to see which kind of value we
60 // captured (quoted or unquoted).
64 // We found a quoted value. When we capture
65 // this value, unescape any double quotes.
66 strMatchedValue = arrMatches[ 2 ].replace(
67 new RegExp( "\"\"", "g" ),
73 // We found a non-quoted value.
74 strMatchedValue = arrMatches[ 3 ];
79 // Now that we have our value string, let's add
80 // it to the data array.
81 arrData[ arrData.length - 1 ].push( strMatchedValue );
84 // Return the parsed data.