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));
添加回答
舉報