Javascript Regex: extracting variables from paths

javascriptregex

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!

Best Answer

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

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

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