在Javascript/jQuery中,如果值是可选的,如何将url拆分为键值对

在Javascript/jQuery中,如果值是可选的,如何将url拆分为键值对,javascript,jquery,regex,Javascript,Jquery,Regex,我想将url拆分为键/值对,除非有时有独立键(不带值)。IE我有一些这种格式的URL: 'first_resources/99/second_resources/41/third_resources/fourth_resources/98' 这里,第一、第二和第四个资源都有ID,但第三个资源没有ID 我希望此输出具有如下数组: [["first_resources",99],["second_resources",41],["third_resources"],["fourth_resour

我想将url拆分为键/值对,除非有时有独立键(不带值)。IE我有一些这种格式的URL:

 'first_resources/99/second_resources/41/third_resources/fourth_resources/98'
这里,第一、第二和第四个资源都有ID,但第三个资源没有ID

我希望此输出具有如下数组:

[["first_resources",99],["second_resources",41],["third_resources"],["fourth_resources",98]]

您可以使用相对简单的正则表达式和
Array.map()
操作来实现这一点:

var re = /(\w+\/\d+)|(\w+)/g,
str = 'first_resources/99/second_resources/41/third_resources/fourth_resources/98',
results;

results = str.match(re).map(function(item) {
  return item.split('/');
})
根据您的目标平台,您可能需要调整垫片