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

前端 未结 17 890
不知归路
不知归路 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条回答
  •  -上瘾入骨i
    2020-11-22 02:16

    People seemed to be against RegEx for this. Why?

    (\s*'[^']+'|\s*[^,]+)(?=,|$)
    

    Here's the code. I also made a fiddle.

    String.prototype.splitCSV = function(sep) {
      var regex = /(\s*'[^']+'|\s*[^,]+)(?=,|$)/g;
      return matches = this.match(regex);    
    }
    
    var string = "'string, duppi, du', 23, 'string, duppi, du', lala";
    var parsed = string.splitCSV();
    alert(parsed.join('|'));
    

提交回复
热议问题