Skip to content Skip to sidebar Skip to footer

Javascript Regex: Extracting Variables From Paths

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

Solution 1:

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

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

matches; // ["firstVar", "secondVar", "thirdVar"]

Solution 2:

What about this:

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

matches:

:firstVar:(secondVar)
:thirdVar

$1 contains:

firstVar
secondVar
thirdVar

Solution 3:

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.

Post a Comment for "Javascript Regex: Extracting Variables From Paths"