Javascript:以逗号分隔的用引号引起来的字符串

Javascript:以逗号分隔的用引号引起来的字符串

问题描述:

我有一个字符串,它本身是一个用逗号分隔的带引号的字符串列表-其中可以有逗号.

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."', '""', '']

有什么建议吗?

谢谢.

您可以将其视为JSON字符串的一部分,并附加必要的部分以将其解析为数组.

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 + ']');
console.log(array);