user2727195 user2727195 - 1 year ago 75
Javascript Question

differentiate between different urls

I am trying to differentiate between different urls. I have an if/else in place but hopefully this can be done better in vanilla js. No express js please.





Current strategy:

if(request.url.indexOf('/product') != -1 && request.url.length == '/product'.length) {

} else if { // /product/:id
if(!request.params) request.params = {}; = request.url.match(/^\/product\/([^\\/]+?)(?:\/(?=$))?$/i)[1];
} else { // 3rd case /product/1/customer


I think my if/else are not resolving to all uri's mentioned above. Please suggest any solution, so that I can resolve all 3 cases from above in a reusable way for different urls, and run appropriate queries from there.

Answer Source

Here is a very basic example that will hopefully put you on the right track. You firstly need to store all the urls you want, and their associated functions that you want to run. Then when a new url comes in, you need to compare it to your stored urls to see if there is a match. As urls can have certain varying values, you need a way to deal with wildcards.

So firstly create a function that adds a particular url scheme, and associated run function to an array.

var myUrls = [];
function addUrl(url, associatedFunc){

        func: associatedFunc,
        parts: url.split('/').map(function(item){
            return item.startsWith(':') ? null : item;

To add a new url you would put : in front of any part of the url that can be wild.

addUlr('/product/:value/customer', doCustomerStuffFunc);

Next you need a way of comparing incoming url requests with your url array.

function resolveUrl(url){

        var pieces = url.split('/');
        if(pieces.length ==={
            for(var i=0; i<pieces.length; i++){
                // check if the piece is valid
                if([i] && pieces[i] !==[i]){

                // if there is an exact match run the function and return
                if(i === pieces.length - 1){ return item.func(pieces); }

This will run the first encountered matches associated function, passing in an array containing all the values in the given url.

Note: This is untested code, written off the top of my head, intended to get you started, and not be a full solution.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download