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


Expected output should be:

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

Tried something like


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!

Best Solution

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

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

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