Jack Evans
Jack Evans

Reputation: 23

JQuery switch based on window.location.pathname with regex

I'm trying to do a switch statement based on window.location.pathname but one of the cases that I'm trying to account for will have a number at the end, anything from 1 to X. What's the best method of tackling this? I've looked into a regex approach but can't seem to get it right.

My code is:

$(document).ready(function() {
    switch (window.location.pathname) {
        case '/dashboard':
            $('.dashboard').addClass('active');
            break;
        case '/dashboard/inquiries':
            $('.inquiries').addClass('active');
            break;
        case '/dashboard/cms':
        case '/dashboard/cms/edit-header':
        case '/dashboard/cms/grid/1234': << this is the part in question.
            $('.cms').addClass('active');
            break;
        default:
            break;
    }
});

Upvotes: 0

Views: 569

Answers (1)

billyonecan
billyonecan

Reputation: 20270

You could remove any digits from the end of the path before your switch:

var x = window.location.pathname.replace(/\/\d+$/, '');

switch (x) {
    ...
    case '/dashboard/cms/grid':
        $('.cms').addClass('active');
        break;
    ...
}

Upvotes: 1

Related Questions