0

I'm using the following JavaScript to get the pathname to show a link is selected:

var pathname = window.location.pathname;

    $(document).ready(function ()
    {

        $('ul#ui-ajax-tabs li a').each(function()
        {
            if ($(this).attr('href') == pathname)
            {
                $(this).parents('li').addClass('selected');
            }
        });
    });

However it has problems if that URL has extra parameters such as / on the end of the url or additional parameters (see examples below) Is it possible to check if the link matches part of the url so for example:

The Link is: /Organisations/Journal/

And the Current page is: /Organisations/Journal/Edit/21

This would class as being selected as it matches part of the url!

Cameron
  • 24,868
  • 91
  • 263
  • 449
  • startsWith method definitions from this question may help to match urls if I understood your question correctly: http://stackoverflow.com/questions/646628/javascript-startswith – reader_1000 Oct 01 '11 at 10:20

2 Answers2

4
window.location.pathname.match('^/Organisations/Journal/');

The ^ character matches the beginning of the string.

mowwwalker
  • 14,309
  • 23
  • 87
  • 144
0

You can probably use indexOf to check if the pathname starts with the value of the href attribute:

if (pathname.indexOf($(this).attr('href')) == 0) {
    ...
}

See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/indexOf for more information on the indexOf method.