3 回答
TA贡献1810条经验 获得超5个赞
RFC 4180溶液
这不能解决问题中的字符串,因为它的格式不符合RFC 4180;可接受的编码是用双引号转义双引号。下面的解决方案可以正确地处理Google电子表格中的CSV文件D/L。
解析单行是错误的。根据rfc 4180字段可能包含crlf,这将导致任何行读取器破坏csv文件。下面是解析CSV字符串的更新版本:
'use strict';
function csvToArray(text) {
let p = '', row = [''], ret = [row], i = 0, r = 0, s = !0, l;
for (l of text) {
if ('"' === l) {
if (s && l === p) row[i] += l;
s = !s;
} else if (',' === l && s) l = row[++i] = '';
else if ('\n' === l && s) {
if ('\r' === p) row[i] = row[i].slice(0, -1);
row = ret[++r] = [l = '']; i = 0;
} else row[i] += l;
p = l;
}
return ret;
};
let test = '"one","two with escaped """" double quotes""","three, with, commas",four with no quotes,"five with CRLF\r\n"\r\n"2nd line one","two with escaped """" double quotes""","three, with, commas",four with no quotes,"five with CRLF\r\n"';
console.log(csvToArray(test));
添加回答
举报