const url = "/animals/15";
const urlList = ['/animals/cats', 'animals/details/subdetails/:id', '/animals/:id', 'smth/else', 'smth/else/:id/:type'];
const matchURL = (url, list) => {
const count = list.length;
for (let index = 0; index < count; index++) {
const template = list[index];
const preparedTemplate = template.replace(/:(\w+)/g, '(?<$1>[^/]+)');
const expression = new RegExp(`^${preparedTemplate}$`, 'gi');
const match = expression.exec(url);
if (match !== null) {
return {
index,
url,
template,
params: match?.groups || {}
};
}
}
return null;
};
matchURL(url, urlList);
/*
{
index: 2,
url: '/animals/15',
template: '/animals/:id',
params: { id: '15' }
}
*/