3

Okay, I've been searching for this for way too long already... I'm trying to find out how I can return the filename of the page that's running an included javascript, from inside that javascript.

I can easily do this in PHP using $_SERVER['SCRIPT_FILENAME'], but in Javascript this seems to be a lot harder.

Do I really need to substring it from location.href or is there a more efficient way? Could jQuery help?

4
  • The location.href solution assumes that your filename is exposed in the URL. It won't work if your URL are rewritten -- see this question's URL. Commented Feb 4, 2010 at 3:38
  • Hmmm, that IS an important note to keep into account - thanks Nikki. Do you happen to know an alternative solution to fix this problem? I'm using it in a jQuery AJAX function, so the PHP solution is no option here, I'm afraid. Commented Feb 6, 2010 at 2:30
  • There are some other possibilities to get to the filename, the question is - what are you trying to do, what are you needing the filename for? Commented Apr 12, 2012 at 11:08
  • It needed to be passed in an AJAX-call. The project in question is no longer relevant, but I am still curious how one might work this out with rewritten URL's. Commented May 3, 2012 at 10:06

2 Answers 2

4

Remove the Url Parameters

function getFileName()
{
  var url = window.location.pathname;
  var lastUri = url.substring(url.lastIndexOf('/')+1);
  if(lastUri.indexOf('?')!= -1)
     return lastUri.substring(0,lastUri.indexOf('?'));
  else
     return lastUri;
}
Sign up to request clarification or add additional context in comments.

Comments

2
var url=location.href;
return url.substring(url.lastIndexOf('/')+1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.