Import CSV (from a String) as an Array (double-quotes support)
/* | |
Syntax : Array importCSV(String text) | |
example : importCSV('ab,cd,ed\n"ab","cd","ef"') | |
*/ | |
function importCSV(text){ | |
text = text.replace(/^[\n\r]+/, "").replace(/[\n\r]+$/, "") + "\n"; | |
var table = [], | |
row = [], | |
indbl = false, | |
start = true, | |
content = ""; | |
for(var i=0, c;i<text.length;i++){ | |
c = text.charAt(i); | |
if(start){ | |
start = false; | |
if(c == '"'){ | |
indbl = true; | |
} | |
else{ | |
content += c; | |
} | |
} | |
else if(c == '"' && indbl){ | |
if(text.charAt(i+1) == '"'){ | |
i++; | |
content += c; | |
} | |
else{ | |
indbl = false; | |
} | |
} | |
else if(c == "," && !indbl){ | |
row.push(content); | |
indbl = false; | |
content = ""; | |
start = true | |
} | |
else if(c == "\n" && !indbl){ | |
row.push(content); | |
indbl = false; | |
content = ""; | |
start = true | |
table.push(row); | |
row = []; | |
} | |
else{ | |
content += c; | |
} | |
} | |
return table; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment