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

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

    Regular expressions to the rescue! These few lines of code handle properly quoted fields with embedded commas, quotes, and newlines based on the RFC 4180 standard.

    function parseCsv(data, fieldSep, newLine) {
        fieldSep = fieldSep || ',';
        newLine = newLine || '\n';
        var nSep = '\x1D';
        var qSep = '\x1E';
        var cSep = '\x1F';
        var nSepRe = new RegExp(nSep, 'g');
        var qSepRe = new RegExp(qSep, 'g');
        var cSepRe = new RegExp(cSep, 'g');
        var fieldRe = new RegExp('(?<=(^|[' + fieldSep + '\\n]))"(|[\\s\\S]+?(? '; // newline representation in case a field contains newlines, default: '\n' 
    var grid = parseCsv(csv, separator, newline);
    // expected: [ [ 'A1', 'B1', 'C1' ], [ 'A "2"', 'B, 2', 'C 
    2' ] ]

    Unless stated elsewhere, you don't need a finite state machine. The regular expression handles RFC 4180 properly thanks to positive lookbehind, negative lookbehind, and positive lookahead.

    Clone/download code at https://github.com/peterthoeny/parse-csv-js

提交回复
热议问题