chris Frisina
chris Frisina

Reputation: 19688

Jquery to get the name of the current html file

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

Upvotes: 32

Views: 71620

Answers (4)

Vyacheslav Voronchuk
Vyacheslav Voronchuk

Reputation: 2463

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 (#).

Upvotes: 49

Vin
Vin

Reputation: 2155

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

Upvotes: 14

Max Kamenkov
Max Kamenkov

Reputation: 2598

location.pathname.split('/').slice(-1)[0]

Upvotes: 26

Z .
Z .

Reputation: 12837

function getCurentFileName(){
    var pagePathName= window.location.pathname;
    return pagePathName.substring(pagePathName.lastIndexOf("/") + 1);
}

Upvotes: 6

Related Questions