javascript csv string with commas in fields

Solutions on MaxInterview for javascript csv string with commas in fields by the best coders in the world

showing results for - "javascript csv string with commas in fields"
Marlene
15 Oct 2018
1// Return array of string values, or NULL if CSV string not well formed.
2function CSVtoArray(text) {
3    var re_valid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*)*$/;
4    var re_value = /(?!\s*$)\s*(?:'([^'\\]*(?:\\[\S\s][^'\\]*)*)'|"([^"\\]*(?:\\[\S\s][^"\\]*)*)"|([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*))\s*(?:,|$)/g;
5    // Return NULL if input string is not well formed CSV string.
6    if (!re_valid.test(text)) return null;
7    var a = [];                     // Initialize array to receive values.
8    text.replace(re_value, // "Walk" the string using replace with callback.
9        function(m0, m1, m2, m3) {
10            // Remove backslash from \' in single quoted values.
11            if      (m1 !== undefined) a.push(m1.replace(/\\'/g, "'"));
12            // Remove backslash from \" in double quoted values.
13            else if (m2 !== undefined) a.push(m2.replace(/\\"/g, '"'));
14            else if (m3 !== undefined) a.push(m3);
15            return ''; // Return empty string.
16        });
17    // Handle special case of empty last value.
18    if (/,\s*$/.test(text)) a.push('');
19    return a;
20};
21
similar questions