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!
Related posts:


8 Responses
Ranjan
20|Dec|2007Can 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.
trent
20|Dec|2007Yes, 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.
Mark
30|Jan|2008@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.
George P.
04|Apr|2008Sorry, this solution doesn’t work when the URL has multiple subdomains.
trent
14|Apr|2008The 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];
}
L^2
07|Sep|2008You may also be interested in toadhall’s 5:49 p.m. post in this forum:
http://www.webmasterworld.com/forum91/386.htm (#:1484829).
trent
07|Sep|2008Thanks,
But I’m just wondering how this solution would work if i had a url like:
http://site.com/foo/bar.cfm/some/vars/here
A lot of coldfusion applications do this since url rewrites aren’t as easy as linux
Shark
06|Feb|2009Thanks for the interesting solution. But it fails to work on my server.
So I have googled it somewhat, and got this function worked for me
[code]
function DocfilenameExtract()
{
wholeurl = document.location.href;
x = wholeurl.length;
while((wholeurl.substring(x,x-1))!= "/"){ x--; } clipstart = x;
return wholeurl.substring(wholeurl.length,clipstart);
}
[/code]
Its taken from here