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

前端 未结 17 1179
不知归路
不知归路 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:03

    I liked FakeRainBrigand's answer, however it contains a few problems: It can not handle whitespace between a quote and a comma, and does not support 2 consecutive commas. I tried editing his answer but my edit got rejected by reviewers that apparently did not understand my code. Here is my version of FakeRainBrigand's code. There is also a fiddle: http://jsfiddle.net/xTezm/46/

    String.prototype.splitCSV = function() {
            var matches = this.match(/(\s*"[^"]+"\s*|\s*[^,]+|,)(?=,|$)/g);
            for (var n = 0; n < matches.length; ++n) {
                matches[n] = matches[n].trim();
                if (matches[n] == ',') matches[n] = '';
            }
            if (this[0] == ',') matches.unshift("");
            return matches;
    }
    
    var string = ',"string, duppi, du" , 23 ,,, "string, duppi, du",dup,"", , lala';
    var parsed = string.splitCSV();
    alert(parsed.join('|'));
    

提交回复
热议问题