How can I parse a CSV string with JavaScript, which contains comma in data?

前端 未结 17 891
不知归路
不知归路 2020-11-22 01:52

I have the following type of string

var string = "\'string, duppi, du\', 23, lala"

I want to split the string into an array on each

17条回答
  •  一生所求
    2020-11-22 02:24

    No regexp, readable, and according to https://en.wikipedia.org/wiki/Comma-separated_values#Basic_rules:

    function csv2arr(str: string) {
        let line = ["",];
        const ret = [line,];
        let quote = false;
    
        for (let i = 0; i < str.length; i++) {
            const cur = str[i];
            const next = str[i + 1];
    
            if (!quote) {
                const cellIsEmpty = line[line.length - 1].length === 0;
                if (cur === '"' && cellIsEmpty) quote = true;
                else if (cur === ",") line.push("");
                else if (cur === "\r" && next === "\n") { line = ["",]; ret.push(line); i++; }
                else if (cur === "\n" || cur === "\r") { line = ["",]; ret.push(line); }
                else line[line.length - 1] += cur;
            } else {
                if (cur === '"' && next === '"') { line[line.length - 1] += cur; i++; }
                else if (cur === '"') quote = false;
                else line[line.length - 1] += cur;
            }
        }
        return ret;
    }
    

提交回复
热议问题