Get filename from URL using Javascript

Description

This snippet will get the filename from the url. The filename is the last part of the URL from the last trailing slash. For example, if the URL is http://www.example.com/dir/file.html then
file.html is the file name.

Explanation

var url = window.location.pathname;

This declares the url variable and adds the current pathname as its value.

var filename = url.substring(url.lastIndexOf('/')+1);
alert(filename);

substring (method) - extract characters from start (parameter).
url is the stringObject url.substring(start)

lastIndexOf (method) - position of last occurrence of specified string value, in this case the '/'

Add one to lastIndexOf because we do not want to return the '/'

Snippet

var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
alert(filename);

Comments

Thats does not return the file name

Actually, that does not define the file name.
I'm bad at explaining... so here's the javascript I use:

function getFileName() {
//this gets the full url
var url = document.location.href;
//this removes the anchor at the end, if there is one
url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
//this removes the query after the file name, if there is one
url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
//this removes everything before the last slash in the path
url = url.substring(url.lastIndexOf("/") + 1, url.length);
//return
return url;
}

Thanks, this was just what I

Thanks, this was just what I needed

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options