获取URL的基本名称,然后将活动类放入导航栏

Example Link: http://localhost/test/page.php

I have a JavaScript code that will put an active class to a navbar if the url of that href ==== current_url.

Current JavaScript (Only puts active class to sidebar)

<script type="text/javascript">
jQuery(function($) {
    var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
    $('ul a').each(function() { 
        if (this.href === path) {
            $(this).addClass('sub-menu active');
            $(this).parent().closest("li").addClass('active');
            $(this).parent().parent().closest("li").addClass('active');
        }
    });
}); 
</script>

I want to make it work also if the link has a page.php?success. There will also be an active class as long as the page.php is there regardless of what is after the ?.

I've tried the following script below to extract the basename but now it doesn't work at all, pages with or without ?.

Tried script (Supposed to put active class to sidebar even if the url has page.php?success in it.

<script type="text/javascript">
jQuery(function($) {
    var patharray = window.location.pathname.split( '/' );
    var reallink = patharray[2]; 
    $('ul a').each(function() { 
        if (this.href === reallink) {
            $(this).addClass('sub-menu active');
            $(this).parent().closest("li").addClass('active');
            $(this).parent().parent().closest("li").addClass('active');
        }
    });
}); 
</script>

With the example link above. The script returns page.php And the href's inside the navbar are just page1.php, page2.php etc... So I know it should work since the retrieved reallink is equal to the href of the navbar.

My sidebar

<li class="sub-menu"> // Sidebar with no submenu
  <a class="" href="page1.php">
    <i class="icon-calendar"></i>
    <span>This is page 1</span>
  </a>
</li>
<li class="sub-menu"> // Sidebar with a submenu
  <a href="javascript:;" class="">
    <i class="icon-group"></i>
    <span>This has sub pages</span>
    <span class="arrow"></span>
  </a>
  <ul class="sub">
    <li><a class="" href="page2.php">This is page 2</a></li>
    <li><a class="" href="page3.php">This is page 3</a></li>
  </ul>
</li>

So the first JavaScript puts an active class both to the parent and the child if the href = url is met. But with the 2nd script nothing works.

I guess changing this line in the First script will make it work

var path = window.location.href.split( '?' )[0];