Skip to content

Instantly share code, notes, and snippets.

@YacheLee
Last active July 12, 2017 07:11
Show Gist options
  • Save YacheLee/fa3594172e719695e42b51d1e2dfb261 to your computer and use it in GitHub Desktop.
Save YacheLee/fa3594172e719695e42b51d1e2dfb261 to your computer and use it in GitHub Desktop.
getMatchByVariables
const _ = require('lodash');
const pathToRegexp = require('path-to-regexp');
const pattern = "/activity/:_id";
const url = "/activity/123";
const match = getMatch({pattern, url});
console.log(match);
function getMatch({pattern, url}){
let keys = [];
let re = pathToRegexp(pattern, keys);
const match = re.exec(url);
if(!match){
return false;
}
else{
const [url, ...values] = match;
keys = keys.map(({name}, index) => {
return {
name,
value: values[index]
};
});
return _.mapKeys(keys,"name");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment