views:

88

answers:

3

Trying to extract variable names from paths (variable is preceded with : ,optionally enclosed by ()), the number of variables may vary

"foo/bar/:firstVar/:(secondVar)foo2/:thirdVar"

Expected output should be:

['firstVar', 'secondVar', 'thirdVar']

Tried something like

"foo/bar/:firstVar/:(secondVar)foo2/:thirdVar".match(/\:([^/:]\w+)/g)

but it doesnt work (somehow it captures colons & doesnt have optional enclosures), if there is some regex mage around, please help. Thanks a lot in advance!

+2  A: 
var path = "foo/bar/:firstVar/:(secondVar)foo2/:thirdVar";

var matches = [];
path.replace(/:\(?(\w+)\)?/g, function(a, b){
  matches.push(b)
});

matches; // ["firstVar", "secondVar", "thirdVar"]
Crescent Fresh
Thank you a lot
+1  A: 

What about this:

/\:\(?([A-Za-z0-9_\-]+)\)?/

matches:

:firstVar
:(secondVar)
:thirdVar

$1 contains:

firstVar
secondVar
thirdVar
knoopx
A: 

May I recommend that you look into the URI template specification? It does exactly what you're trying to do, but more elegantly. I don't know of any current URI template parsers for JavaScript, since it's usually a server-side operation, but a minimal implementation would be trivial to write.

Essentially, instead of:

foo/bar/:firstVar/:(secondVar)foo2/:thirdVar

You use:

foo/bar/{firstVar}/{secondVar}foo2/{thirdVar}

Hopefully, it's pretty obvious why this format works better in the case of secondVar. Plus it has the added advantage of being a specification, albeit currently still a draft.

Bob Aman
Thanks for info, but binded by format (its Horde_Routes syntax)
Ah, yes. Another project infected by Rails-esque routing. Oh well, worth a shot.
Bob Aman