Replaced YQL data source with CSV
[marketstoday] / src / qml / Library / js / CSVUtility.js
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 || ",");
9
10     // Create a regular expression to parse the CSV values.
11     var objPattern = new RegExp(
12         (
13             // Delimiters.
14             "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
15
16             // Quoted fields.
17             "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
18
19             // Standard fields.
20             "([^\"\\" + strDelimiter + "\\r\\n]*))"
21         ),
22         "gi"
23         );
24
25
26     // Create an array to hold our data. Give the array
27     // a default empty first row.
28     var arrData = [[]];
29
30     // Create an array to hold our individual pattern
31     // matching groups.
32     var arrMatches = null;
33
34
35     // Keep looping over the regular expression matches
36     // until we can no longer find a match.
37     while (arrMatches = objPattern.exec( strData )){
38
39         // Get the delimiter that was found.
40         var strMatchedDelimiter = arrMatches[ 1 ];
41
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.
46         if (
47             strMatchedDelimiter.length &&
48             (strMatchedDelimiter !== strDelimiter)
49             ){
50
51             // Since we have reached a new row of data,
52             // add an empty row to our data array.
53             arrData.push( [] );
54
55         }
56
57
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).
61         var strMatchedValue;
62         if (arrMatches[ 2 ]){
63
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" ),
68                 "\""
69                 );
70
71         } else {
72
73             // We found a non-quoted value.
74             strMatchedValue = arrMatches[ 3 ];
75
76         }
77
78
79         // Now that we have our value string, let's add
80         // it to the data array.
81         arrData[ arrData.length - 1 ].push( strMatchedValue );
82     }
83
84     // Return the parsed data.
85     return( arrData );
86 }