How to get specific part of link by jquery?

jquery-ui
jquery

#1

hi i want to add active class to target links in menu. so i have to check target link and add active class to related link in menu bar,
like below
for example if i have "mysite.com/home/public/user/manage" i will split the link and recognize its user page so i have to assign active class to user item in menu bar by jquery.

i did something by below code:

  jQuery(document).ready(function($){
            // make current item active
            var path = window.location.pathname.split("/").pop();
            var pathArray = window.location.pathname.split( '/' );
            var pathsec=pathArray[3];
            // Account for home page with empty path
            switch (pathsec) {
         
                case 'operation':
                    var target = $('ul li#manageoperation');
                    break;
                case 'user':
                    var target = $('ul li#manageuser');
                    break;
                case 'meta':
                    var target = $('ul li#mobilehome');
                    break;
                case 'report':
                    var target = $('ul li#report');
                    break;
                default:
                    var target = $('ul li#index');
            }
            // Add active class to target link
            target.addClass('active');

        });

but if i use my script in another domain or sub-domain i have to edit jquery (change index number of pathArray[3]) code for recognize right part...

how can i find path part without changing this array? using another ways?


#2

If you know for a fact that the element will be the second-to-last, you can say pathArray[pathArray.length - 2].

The lesson to learn is to work from the fixed point - in this case, if you know it will always be second-to-last, your fixed point is the end of the array.
array.length will always be 1 more than the index of last element of the array (because arrays start at index 0), so you can work backwards from it.

If your fixed point is the start of the array, you're working from 0 - it may help you to visualize it as pathArray[0+3]. startpoint+distance (even if the distance is negative)