1

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!

3
  • What exactly are you trying to capture here? Can you tell us what results you expect? Commented Nov 22, 2009 at 23:19
  • these are strings, so dont quite get what do you mean by newlines Commented Nov 22, 2009 at 23:21
  • I'm confused by this question. Why would you want to do this? Why does the URL look so mangled? Why aren't you extracting variables from a query segment? Commented Nov 22, 2009 at 23:45

3 Answers 3

3
var path = "foo/bar/:firstVar/:(secondVar)foo2/:thirdVar";

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

matches; // ["firstVar", "secondVar", "thirdVar"]
Sign up to request clarification or add additional context in comments.

Comments

2

What about this:

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

matches:

:firstVar
:(secondVar)
:thirdVar

$1 contains:

firstVar
secondVar
thirdVar

Comments

0

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.

2 Comments

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.