Mac Mac - 1 month ago 5x
Javascript Question

Javascript: Split Comma Delimited Quoted Strings

I have a single string, which is itself a comma delimited list of quoted strings - which can have commas within them.


var str = '"long one","short","oh, look","wow.", ""';

I need to split this into an array:

['long one', 'short', 'oh, look', 'wow.', '']

// will take this if it is easier
['"long one"', '"short"', '"oh, look"', '"wow."', '""']

I tried splitting by
but it throws off entries with a comma in them. I also tried splitting by
, but it creates lob-sided string:

['"long one', '"short', '"oh, look', '"wow.', '"']

I tried splitting by
but causes the same issue but just for the first and last entry:

['"long one', 'short', 'oh, look', 'wow.', '"']

I also tried the regex expression found in this answer, but it adds an empty entry at the start and end of the array:

['', '"long one"', '"short"', '"oh, look"', '"wow."', '""', '']

Any suggestions?



You could treat it as part of a JSON string and append the necessary parts for parsing as array.

var string ='"long one","short","oh, look","wow.", ""',
    array = JSON.parse('[' + string + ']');