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

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

    PEG(.js) grammar that handles RFC 4180 examples at http://en.wikipedia.org/wiki/Comma-separated_values:

    start
      = [\n\r]* first:line rest:([\n\r]+ data:line { return data; })* [\n\r]* { rest.unshift(first); return rest; }
    
    line
      = first:field rest:("," text:field { return text; })*
        & { return !!first || rest.length; } // ignore blank lines
        { rest.unshift(first); return rest; }
    
    field
      = '"' text:char* '"' { return text.join(''); }
      / text:[^\n\r,]* { return text.join(''); }
    
    char
      = '"' '"' { return '"'; }
      / [^"]
    

    Test at http://jsfiddle.net/knvzk/10 or https://pegjs.org/online.

    Download the generated parser at https://gist.github.com/3362830.

提交回复
热议问题