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

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

    According to this blog post, this function should do it:

    String.prototype.splitCSV = function(sep) {
      for (var foo = this.split(sep = sep || ","), x = foo.length - 1, tl; x >= 0; x--) {
        if (foo[x].replace(/'\s+$/, "'").charAt(foo[x].length - 1) == "'") {
          if ((tl = foo[x].replace(/^\s+'/, "'")).length > 1 && tl.charAt(0) == "'") {
            foo[x] = foo[x].replace(/^\s*'|'\s*$/g, '').replace(/''/g, "'");
          } else if (x) {
            foo.splice(x - 1, 2, [foo[x - 1], foo[x]].join(sep));
          } else foo = foo.shift().split(sep).concat(foo);
        } else foo[x].replace(/''/g, "'");
      } return foo;
    };
    

    You would call it like so:

    var string = "'string, duppi, du', 23, lala";
    var parsed = string.splitCSV();
    alert(parsed.join("|"));
    

    This jsfiddle kind of works, but it looks like some of the elements have spaces before them.

提交回复
热议问题