javascript拆分,不带子字符串

时间:2018-08-30 04:43:27

标签: javascript split

我有一个看起来像这样的字符串

"a,b,c,"Mozilla/5.0,(compatible;,MSIE,9.0;,Windows,NT,6.1;,Trident/5.0)",d,e"

我正在尝试用“,”分割此字符串,并提取各个值。现在,它的作用是,将“ Mozilla / 5.0,(compatible;,MSIE,9.0;,Windows,NT,6.1;,Trident / 5.0)”部分也拆分为最终结果

["a", "b", "c", ""Mozilla/5.0", "(compatible;", "MSIE", "9.0;", "Windows", "NT", "6.1;", "Trident/5.0)"", "d", "e"]

有没有一种方法可以使它不拆分子字符串?基本上我想在拆分后得到这个

["a", "b", "c", "Mozilla/5.0,(compatible;,MSIE,9.0;,Windows,NT,6.1;,Trident/5.0)", "d", "e"]

1 个答案:

答案 0 :(得分:6)

您可以使用正则表达式,并对非"字符使用否定的超前查询,后跟",,以表明当前逗号在带引号的字符串内:

const str = `a,b,c,"Mozilla/5.0,(compatible;,MSIE,9.0;,Windows,NT,6.1;,Trident/5.0)",d,e,"foo,bar,quoted",f,g`;
console.log(str.split(/,(?![^"]+",)/))