Skip to content

Instantly share code, notes, and snippets.

@JDMCreator
Created July 31, 2017 00:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JDMCreator/c0944e1caab3b913353ac165177b5241 to your computer and use it in GitHub Desktop.
Save JDMCreator/c0944e1caab3b913353ac165177b5241 to your computer and use it in GitHub Desktop.
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