Search code examples
javascriptregexurlurl-routing

Matching a string to one of many patterns and extracting data


I have a problem I want to solve with RegEx, or any other method if there is a better one. I've tried several ways to achieve the goal, but nothing really worked.

I have an array with endpoints:

const endpoints = [
    {
        id: 1,
        url: "/api/items/:itemId"
    },
    {
        id: 2,
        url: "/api/users/:userName/delete"
    },
    {
        id: 3,
        url: "/api/users/:userName/edit"
    }
];

And a request URL:

const url = "/api/users/max/edit";

Now what I want is to have a function which acts like this:

const rewrite = (url, endpoints) => {

    // What is the best way to achieve the following return value:

    return {
        endpointId: 3,
        values: {
            userName: "max"
        }
    };
};

Explanation: The function should find the appropriate endpoint for the url. All parts of the endpoint url which start with a colon are not static, but should rather be replaced with values from the request url. In this case :userName should be replaced with max.

I've been in web development for some time now, but to be honest I've almost no clue how to solve such a problem.


Solution

  • const rewrite = (url, endpoints) => {
        var doubledArray = Array.prototype.map.call(endpoints, function(el) {
            return {
                id: el.id,
                url: el.url.split('/')
            };
        });
    
        var parts = url.split('/');
        var i = 0;
        parts.forEach(function(element) {
            doubledArray = doubledArray.filter(el => (element == el.url[i] || el.url[i].startsWith(':')));
            i++;
        });
    
        return {
            endpointId: doubledArray[0].id,
            values: {
                [`${doubledArray[0].url.filter(el => el.startsWith(':'))[0].substring(1)}`]: parts[doubledArray[0].url.findIndex(function (el) { return el.startsWith(':'); } )],
            }
        };
    
    };