2013-03-26 21 views
0

我想将url分割为键/值对,但有时候会有独立键(不带值)。 IE我有这种格式的一些网址:如何在JavaScript/jQuery中将值分成可选的值时将url分割为键值对

'first_resources/99/second_resources/41/third_resources/fourth_resources/98' 

这里,第一,第二和第四资源有ID,但第三资源没有。

我想有这种输出一个这样的数组:

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

回答

2

你可以用相对简单的正则表达式和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('/'); 
}) 

,您可能需要垫片Array.map