javascript用逗号分割字符串忽略引号内

时间:2012-11-09 21:35:40

标签: javascript regex

  

可能重复:
  Javascript code to parse CSV data

我有这个字符串:

"display, Name" <test@test.com>, display" Name <test@test.com>, test@test.com

我想将此字符串分隔为数组

array[0] = "\"display, Name\" <test@test.com>"
array[1] = "display\" Name <test@test.com>"
array[2] = "test@test.com"

这是我的代码:

var comma = inQuotes = false;
for(var i=0;i<str.length;i++) {
            if (str[i] == '"') inQuotes = !inQuotes;
            comma = (str[i] == "," && !inQuotes)  ? true : false;
            item += (!comma) ? str[i] : "";
            if(comma || i == str.length-1) {  
                items.push(item);
                item = "";
            }    
        } 

我的问题是,如果你有一个双引号而没有字符串中的近距离

我很感激帮助...

1 个答案:

答案 0 :(得分:1)

我尝试了这个,它适用于上面的字符串jsfiddle

var a = '"display, Name" <test@test.com>, display" Name <test@test.com>, test@test.com';
var aa = a.match(/"(.*?)"(.*?),|(.*?),|(.*?)$/g); 
aa.pop();
aa // [""display, Name" <test@test.com>,", " display" Name <test@test.com>,", " test@test.com"]