Home » Html » How can i get the name of an html page in Javascript?

How can i get the name of an html page in Javascript?

Posted by: admin November 29, 2017 Leave a comment

Questions:

i have an html page and i would like inside the html page
to retrieve the name of the html document
via Javascript. Is that possible?

e.g. name of html document = "indexOLD.html"

Answers:
var path = window.location.pathname;
var page = path.split("/").pop();
console.log( page );

Questions:
Answers:

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

Questions:
Answers:

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 extaract it using substring method.

Questions:
Answers:

Use: location.pathname

alert(location.pathname);

http://jsfiddle.net/yQqe3/

https://developer.mozilla.org/en-US/docs/DOM/window.location

Questions:
Answers:

Use window.location.pathname to get the path of the current page’s URL.

Questions:
Answers:

This will work even if the url ends with a /:

var segments = window.location.pathname.split('/');
var toDelete = [];
for (var i = 0; i < segments.length; i++) {
    if (segments[i].length < 1) {
        toDelete.push(i);
    }
}
for (var i = 0; i < toDelete.length; i++) {
    segments.splice(i, 1);
}
var filename = segments[segments.length - 1];
console.log(filename);