Get filename from URL using Javascript

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 '/'

Full snippet

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

Comments

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;
}

DEO, Just what I was looking for thank you.

Nice function! It deals with all situation! Thanks!

Thanks, this was just what I needed

Thanks!! :)

thanx man

Thank you it helped me to solve a issue

thanks

Thanks.... nice info

thanks

Note that this returns an empty string if the filename part of the URL is empty, eg "http://www.google.co.uk/".

Post new comment

The content of this field is kept private and will not be shown publicly.

Learn how to write custom Drupal modules

Does Drupal module development make your head explode and drive you crazy?

Why not learn from someone who has paved the way instead?

Sign up to Master Drupal 7 Module Development.

Hello!!

I am Blair Wadman and this is where I write about Drupal, PHP, CSS etc

Stuff

Syndicate

Syndicate content

© Blair Wadman
2005 - 2011