JavaScript:拆分字符串而不拆分子字符串

时间:2016-07-21 13:35:28

标签: javascript string split

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

var str = "'1vK3KfqgSHqv5Y0066FnIY',#41,$,$,(#149,#488,#862,#945,#1028,#1249),#114";

通常我会:

str.split(",");

但这会导致:

[
    "'1vK3KfqgSHqv5Y0066FnIY'", 
    "#41", 
    "$", 
    "$", 
    "(#149", 
    "#488", 
    "#862", 
    "#945", 
    "#1028", 
    "#1249)", 
    "#114"
]

期望的结果是:

[
    "'1vK3KfqgSHqv5Y0066FnIY'", 
    "#41", 
    "$", 
    "$", 
    "(#149, #488, #862, #945, #1028, #1249)", 
    "#114"
]

我将如何实现这一目标?

1 个答案:

答案 0 :(得分:3)

你好,这是一个正则表达式

str.match(/(\(.*?\)|[^\(,\s]+)(?=\s*,|\s*$)/g)

导致

[ '\'1vK3KfqgSHqv5Y0066FnIY\'',
  '#41',
  '$',
  '$',
  '(#149,#488,#862,#945,#1028,#1249)',
  '#114' ]