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.
Just make this into a function as below:
Then when you need to use it:
All of the "ugliness" has been hidden in a function and the main code looks nice and clean!
For work with querystring like http://www.example.com/keyword/category.php?parametro=teste
Note: If you do
.split('.')
, you will miss the base names of many URLs.You can find the last forward slash and search ahead for the first
.
,?
,&
or#
to catch variations of URLs. This is probably the equivalent of PHP's basenameand use it like so
Results:
JSBin demo