'How to test routes using regEx in JavaScript

I have some routes in my Node Js single plage application which update without page load. I wanna test some routes using regEx to get a perfect match of the route.

I have /index, /contact, /products in switch statement.

    switch(window.location.pathname)
        case '/index':
            break;
         case '/contact':
            break;
         case '/products':
            break;
    default:
            //Returning error page if none of pathname met
             break;

How can I make it possible for a user to visit /products/iphone or /products/:brandName/:productId and be able to get the values of :brandName and :productId in JavaScript using regEx in vanilla JavaScript



Solution 1:[1]

You could do something like this - since the "parts" of the pathname are always separated by / there's no need for the complexity of a regex - a simple .split will do just fine

// the leading , is NOT a typo
const [, root, ...rest] = location.pathname.split('/');

switch (root)
case '/index':
    break;
case '/contact':
    break;
case '/products': {
        const [brandName, productId, ...more] = rest;
        // brandName and productId will be the first two parts of the path after /products
    }
    break;
default:
    //Returning error page if none of pathname met
    break;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bravo