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

Here’s what I would do.

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

enter image description here
/* 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 Comment