开发者

Javascript Regex: extracting variables from paths

开发者 https://www.devze.com 2022-12-12 19:02 出处:网络
Trying to extract variable names from paths (variable is preceded with : ,optionally enclosed by ()), the number of variables may vary

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', 'sec开发者_如何学编程ondVar', '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!


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

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

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


What about this:

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

matches:

:firstVar
:(secondVar)
:thirdVar

$1 contains:

firstVar
secondVar
thirdVar


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消