Blair Wadman 1 minute read
February 3, 2020

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