How to get specific part of link by jquery?

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 “” 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:

            // 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');
                case 'user':
                    var target = $('ul li#manageuser');
                case 'meta':
                    var target = $('ul li#mobilehome');
                case 'report':
                    var target = $('ul li#report');
                    var target = $('ul li#index');
            // Add active class to target link


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?

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)

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.