Get file name in javascript

How to get the file name of the page? When you need to read the file name of the current…

November 25, 2010

How to get the file name of the page? When you need to read the file name of the current page in javascript you can use the document.location.href string and parse it to find the filename, here is the script that strips away the other chars and keep only the script file name:

function getFileName() {
	var url = document.location.href;
	url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
	url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
	url = url.substring(url.lastIndexOf("/") + 1, url.length);
	return url;
}

Another usefull function is the one that get the parameters from the url.

Author

I'm a software engineer, an everyday web developer and a maker. I usually build sites with PHP, within or without WordPress. I build Internet of Things with Arduino and ESP8266. I'm the founder of Rockit.it and Dailybest.it and I'm actually the Chief Technical Officer of Better Days web agency.

Comments on “Get file name in javascript”

2 thoughts

  1. Jeff says:

    Most excellent! Thanks!

Comments are closed

Recommended

Get URL parameter in javascript

Sometimes in javascript you have the variable that you need to use in the url, as a parameter passed in…

Add Internet Explorer class to body to detect old browser

When you have clients that still uses an old browser, you need to handle it. This javascript function detects the…

February 27, 2017

Modify list counter in :before pseudo class with jQuery using start attribute

Suppose you have two ordered list ol tags, and the second one has a start attribute. You also have in…

April 20, 2016

Refresh a Google Adsense banner with Javascript

Often bloggers and site owners use galleries to have a greater number of pages, adding pages means adding clicks. Each…

November 9, 2013

Detect if is mobile with Javascript, read user agent

How to detect if your user is using a mobile device in Javascript? You can do it by checking the…

November 5, 2013

Unobtrusive javascript to add an overlay banner

If you have to add an overlay to a site, here is a fast way to do it with an…

November 7, 2011