31

If you are on http://www.cnn.com/2012/11/09/opinion/brown-pakistan-malala/index.html can you get Jquery to grab the index.html?

or if you are on http://www.washingtonpost.com/politics/decision2012/supreme-court-to-review-key-section-of-voting-rights-act/2012/11/09/dd249cd0-216d-11e2-8448-81b1ce7d6978_story.html have it return dd249cd0-216d-11e2-8448-81b1ce7d6978_story.html?

And for non extension defined pages such as this current one http://stackoverflow.com/questions/13317276/jquery-to-get-the-name-of-the-current-html-file can it return the last "file" in the "directory"structure, for example: jquery-to-get-the-name-of-the-current-html-file

chris Frisina
  • 19,086
  • 22
  • 87
  • 167
  • Try checking this question out http://stackoverflow.com/questions/1302306/how-to-pull-the-file-name-from-a-url-using-javascript-jquery – aeternus828 Nov 09 '12 at 23:02
  • 3
    What if the current page is simply `http://stackoverflow.com/`? Do you just want "stackoverflow.com"? – nnnnnn Nov 09 '12 at 23:11
  • good clarification, yes, the last of the path name is what I am looking for – chris Frisina Nov 09 '12 at 23:49
  • I am using this code document.location.pathname.match(/[^\/]+$/)[0] but when I am in my base link for example `http://stackoverflow.com/` it is throwing error in console, Is there some way to validate it ? – Hitesh Nov 14 '14 at 05:10

4 Answers4

49

Although not JQuery, you can access it using the following:

document.location.href.match(/[^\/]+$/)[0]

or

document.location.pathname.match(/[^\/]+$/)[0] in case of unneeded anchors/hash tags (#).

chris Frisina
  • 19,086
  • 22
  • 87
  • 167
Vyacheslav Voronchuk
  • 2,403
  • 19
  • 16
  • I am using this code document.location.pathname.match(/[^\/]+$/)[0] but when I am in my base link for example `http://www.cnn.com` it is throwing error in console, Is there some way to validate it ? – Hitesh Nov 14 '14 at 05:09
26
location.pathname.split('/').slice(-1)[0]
Max Kamenkov
  • 2,478
  • 3
  • 22
  • 19
14

No need for jQuery. This will give you the last segment of the URL path (the bit after the last slash):

var href = document.location.href;
var lastPathSegment = href.substr(href.lastIndexOf('/') + 1);
Vin
  • 1,975
  • 5
  • 27
  • 34
6
function getCurentFileName(){
    var pagePathName= window.location.pathname;
    return pagePathName.substring(pagePathName.lastIndexOf("/") + 1);
}
Z .
  • 12,657
  • 1
  • 31
  • 56