How can I get the name of an html page in Javascript?
var path = window.location.pathname;
var page = path.split("/").pop();
console.log( page );
Current page: It's possible to do even shorter. This single line sound more elegant to find the current page's file name:
var fileName = location.href.split("/").slice(-1);
or...
var fileName = location.pathname.split("/").slice(-1)
This is cool to customize nav box's link, so the link toward the current is enlighten by a CSS class.
JS:
$('.menu a').each(function() {
if ($(this).attr('href') == location.href.split("/").slice(-1)){ $(this).addClass('curent_page'); }
});
CSS:
a.current_page { font-size: 2em; color: red; }
Try this
location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
location.pathname gives the part (domain not included) of the page URL. To get only the filename you have to extract it using the substring method.