View Full Version : parsing out basename from location.pathname?

05-09-2006, 01:46 AM
I can do this easily in PHP but how can I get just the filename (with no extension or domain) in Javascript.


Will return: "etc/etc/etc/bobs_page.html"

But I only want "bobs_page" read into my variable. Does javascript have an equivilant to getBaseName?

Thank you.

05-09-2006, 02:49 AM
var path_name=location.pathname;
var base_name=path_name.lastIndexOf("/")+1;

05-09-2006, 03:30 AM
Hey thanks!!
Exactly what I was looking for; here is how I finished it after looking up 'substring' and 'lastIndexOf' based on your suggestion.

// get instructor name
var pathName=location.pathname;
var startLoc=pathName.lastIndexOf("/")+1;
var endLoc=pathName.lastIndexOf("html")-1;
var instructorName = pathName.substring(startLoc, endLoc);

05-09-2006, 06:22 AM
You can also take out the 'var endLoc' line and just do:

var instructorName=pathName.substring(startLoc, pathName.length-5);

It does the same thing as the endLoc variable but it basially counts how many characters are in the whole string and then subtracts 5 characters from the end of the string and those 5 characters will be '.html'. Its just a shorter way to do the same thing, just giving you some options.