Split a string by commas but ignore commas within double-quotes using Javascript

I’m looking for [a, b, c, "d, e, f", g, h]to turn into an array of 6 elements: a, b, c, “d,e,f”, g, h. I’m trying to do this through Javascript. This is what I have so far:

str = str.split(/,+|"[^"]+"/g); 

But right now it’s splitting out everything that’s in the double-quotes, which is incorrect.

Edit: Okay sorry I worded this question really poorly. I’m being given a string not an array.

var str = 'a, b, c, "d, e, f", g, h';

And I want to turn that into an array using something like the “split” function.

Answer

Here’s what I would do.

var str = 'a, b, c, "d, e, f", g, h';
var arr = str.match(/(".*?"|[^",s]+)(?=s*,|s*$)/g);
/* will match:

    (
        ".*?"       double quotes + anything but double quotes + double quotes
        |           OR
        [^",s]+    1 or more characters excl. double quotes, comma or spaces of any kind
    )
    (?=             FOLLOWED BY
        s*,        0 or more empty spaces and a comma
        |           OR
        s*$        0 or more empty spaces and nothing else (end of string)
    )

*/
arr = arr || [];
// this will prevent JS from throwing an error in
// the below loop when there are no matches
for (var i = 0; i < arr.length; i++) console.log('arr['+i+'] =',arr[i]);

Leave a Reply

Your email address will not be published. Required fields are marked *