Thu 25 Oct 2007
So I stumbled into a problem where I didn’t want to actually use server side code to actually write javascript. I have an accordian menu, and according to which subpage I am on I want to show that part of the accordian menu automatically on page load. My task became to retrieve just the name of the file name. This isn’t a solution for clean url’s, as that could get a good bit more tricky( http://www.abc.com/first/second/third/forth/, which one is the actual file???). Luckily for me I’m upgrading some slightly older code and mine uses regular old url’s.
Basically the easiest solution I came up with is to use a regular expression to pull out all occurances of a /file.ext and then return the first occurance. So my solution looked like this:
function getFileName(path){
var fn = path.match(/\/([a-z0-9_-]+\.\w+)/i);
return (fn == null)? “” : fn[1];}
Pretty simple solution right? Where path is the full url, we perform a match to get all matches. If it found no matches we return “”. This means the file may not be within the url in the case that it is index.html or home.html, etc where it is the default. Hope this helps someone!

December 20th, 2007 at 7:14 am
Can we directly retrieve the file name of the current page using javascript without supplying the page URL manually. Javascript code should automatically get the URL and get the file name.
December 20th, 2007 at 8:46 am
Yes, javascript can get the url. but picking the filename out of the url is what this does. I dont know of any js function to give the file name.
January 30th, 2008 at 6:29 am
@Ranjan
You can use window.location.href to get the path of the current file without entering it manually, but you still have to manipulate it to get the actual filename.
April 4th, 2008 at 10:10 am
Sorry, this solution doesn’t work when the URL has multiple subdomains.
April 14th, 2008 at 12:41 pm
The problem lies within the regular expression. I should have used $ to go to the end of the input string. Also as a fail-safe return the last element found..:
function getFileName(path){
var fn = path.match(/\/([a-z0-9_-]+\.\w+)$/i);
return (fn == null)? “” : fn[fn.length-1];
}