Skip to content

Instantly share code, notes, and snippets.

@chhornponleu
Last active September 19, 2023 08:20
Show Gist options
  • Select an option

  • Save chhornponleu/9a7c68a5eb98af82a26a3eb6ced72a96 to your computer and use it in GitHub Desktop.

Select an option

Save chhornponleu/9a7c68a5eb98af82a26a3eb6ced72a96 to your computer and use it in GitHub Desktop.
extract params from route path
function matchRoute(url, routes) {
let route = null;
let exactMatchRoute = null;
for (let i = 0; i < routes.length; i++) {
const routePath = routes[i].path;
const routeName = routes[i].name;
const handler = routes[i].handler;
const routeParams = {};
const urlParts = url.split('/');
const routeParts = routePath.split('/');
const queryParams = url.split('?');
if (queryParams.length > 1) {
const pairs = queryParams[1].split('&');
for (let k = 0; k < pairs.length; k++) {
const pair = pairs[k].split('=');
routeParams[pair[0]] = decodeURIComponent(pair[1]);
}
}
// Check for named parameters match
if (urlParts.length === routeParts.length) {
let match = true;
for (let j = 0; j < routeParts.length; j++) {
if (routeParts[j].charAt(0) === ':') {
const paramName = routeParts[j].substr(1);
// extract query param from url path
const queryParams = urlParts[j].split('?');
// set route param. route param will override url query param
routeParams[paramName] = decodeURIComponent(queryParams[0]);
} else if (routeParts[j] !== urlParts[j]) {
match = false;
break;
}
}
if (match) {
route = {
exact:false,
handler: handler,
name: routeName,
path: routePath,
params: routeParams
};
}
}
// Check for exact match
if (url?.split('?')[0] === routePath) {
exactMatchRoute = {
exact:true,
handler: handler,
name: routeName,
path: routePath,
params: routeParams
};
break;
}
}
// Return the exact match route if one exists, otherwise return the named parameter route
return exactMatchRoute || route;
}
const routes = [
{
path: '/product/home',
name: 'product',
handler(url, data) {
console.log(url, data)
}
},
{
path: '/product/:id',
name: 'product',
handler(url, data) {
console.log(url, data)
}
},
{
path: '/product/home1',
name: 'product',
handler(url, data) {
console.log(url, data)
}
},
]
console.log([
matchRoute('/product/home', routes),
matchRoute('/product/13', routes),
matchRoute('/product/home1?name=Hello', routes),
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment