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

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

    My answer presumes your input is a reflection of code/content from web sources where single and double quote characters are fully interchangeable provided they occur as an non-escaped matching set.

    You cannot use regex for this. You actually have to write a micro parser to analyze the string you wish to split. I will, for the sake of this answer, call the quoted parts of your strings as sub-strings. You need to specifically walk across the string. Consider the following case:

    var a = "some sample string with \"double quotes\" and 'single quotes' and some craziness like this: \\\" or \\'",
        b = "sample of code from JavaScript with a regex containing a comma /\,/ that should probably be ignored.";
    

    In this case you have absolutely no idea where a sub-string starts or ends by simply analyzing the input for a character pattern. Instead you have to write logic to make decisions on whether a quote character is used a quote character, is itself unquoted, and that the quote character is not following an escape.

    I am not going to write that level of complexity of code for you, but you can look at something I recently wrote that has the pattern you need. This code has nothing to do with commas, but is otherwise a valid enough micro-parser for you to follow in writing your own code. Look into the asifix function of the following application:

    https://github.com/austincheney/Pretty-Diff/blob/master/fulljsmin.js

提交回复
热议问题