• support@answerspoint.com

How to get the pagename from the URL without the extension through JQuery

672

I have a URL:-

http://www.example.com/keyword/category.php

or

http://www.example.com/keyword/category.php#4

I need a magic abracadabra which gives me only the pagename as category from this URL.

Here is what I tried, and it gives category.php. But it has two problems. It is ugly and long and it gives me filename with an extension.

var currurl = window.location.pathname;
var index = currurl.lastIndexOf("/") + 1;
var filename = currurl.substr(index);

Thanks.

  • jQuery

  • asked 2 years ago
  • Gul Hafiz

1Answer


0

Just make this into a function as below:

function getPageName(url) {
    var index = url.lastIndexOf("/") + 1;
    var filenameWithExtension = url.substr(index);
    var filename = filenameWithExtension.split(".")[0]; // <-- added this line
    return filename;                                    // <-- added this line
}

Then when you need to use it:

var url = "http://www.example.com/keyword/category.php";
var myFilename = getPageName(url);

All of the "ugliness" has been hidden in a function and the main code looks nice and clean!

  • answered 2 years ago
  • Community  wiki

Your Answer

    Facebook Share        
       
  • asked 2 years ago
  • viewed 672 times
  • active 2 years ago

Hot Questions