Created
July 31, 2017 00:22
-
-
Save JDMCreator/c0944e1caab3b913353ac165177b5241 to your computer and use it in GitHub Desktop.
Import CSV (from a String) as an Array (double-quotes support)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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