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!