Javascript:以逗号分隔的用引号引起来的字符串 [英] Javascript: Split Comma Delimited Quoted Strings

查看:41
本文介绍了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);

这篇关于Javascript:以逗号分隔的用引号引起来的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆