Note: If you do .split('.') like other solutions instruct, you will miss the base names from many URLs.
You can find the last forward slash and search ahead for the first ., ?, & or # to catch variations of URLs. This is the equivalent of PHP's basename
function getBaseName(url) {
if(!url || (url && url.length === 0)) {
return "";
}
var index = url.lastIndexOf("/") + 1;
var filenameWithExtension = url.substr(index);
var basename = filenameWithExtension.split(/[.?&#]+/)[0];
// Handle '/mypage/' type paths
if(basename.length === 0) {
url = url.substr(0,index-1);
basename = getBaseName(url);
}
return basename ? basename : "";
}
and use it like so
var url = "http://www.example.com/whaterver/mypage.html";
var file = getBaseName(url);
of
var file = getBaseName(location.pathname); // The current script page
Results:
http://www.example.com/whaterver/mypage/ => "mypage"
http://www.example.com/whaterver/mypage.html => "mypage"
http://www.example.com/whaterver/mypage => "mypage"
http://www.example.com/whaterver/mypage/ => "mypage"
http://www.example.com/whaterver/mypage#works => "mypage"
http://www.example.com/whaterver/mypage?ver=1 => "mypage"