How to get the pagename from the URL without the extension through JQuery
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 7 years ago
- Gul Hafiz
1Answer
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 7 years ago
- Community wiki
Your Answer