JavaScript equivalent to basename ($PHP_SELF);

What is the best way to get just the script name that is running without the path and parameter info? This would be the JavaScript equivalent to the PHP command:
basename ($PHP_SELF);



Have fun!


Thanks, but document.URL gives the entire url, I want just the file name portion. Is there a property or an easy way to split out myfile.html from*test3=2

? Has to be an easy way !

Following is a description of each part of the URL diagram:

protocol represents the beginning of the URL, up to and including the first colon.
host represents the host and domain name, or IP address, of a network host.
port represents the communications port that the server uses for communications.
pathname represents the url-path portion of the URL.
hash represents an anchor name fragment in the URL, including the hash mark (#). This property applies to http URLs only.
search represents any query information in the URL, including the question mark (?). This property applies to http URLs only. The search string contains variable and value pairs; each pair is separated by an ampersand (&).

The above is very nice, but nowhere the actual file name without the path. Dave:bawling:


Hey guys,

Firstly, document.url is deprecated. I’m sure it still returns the correct value, but just FYI, use the window.location object. On that note, you can get just the filename and all that good stuff…just requires a little work.

var splitAt=location.href.lastIndexOf('\\\\') > location.href.lastIndexOf('/') ? location.href.lastIndexOf('\\\\') : location.href.lastIndexOf('/');
var filename= location.href.substr(splitAt+1,location.href.length);

aDog :cool:

you can use location.pathname to make the code a little easier. With this code, you can also set a default page to return in case the href ends with a folder name.

baseName = window.location.pathname.substring(window.location.pathname.lastIndexOf("/")+1) || "index.html";

Ahhh, nice pdlob…guess I didn’t know about the pathname property…guess I should’ve looked up the location object in a reference first :smiley:

aDog :cool: