I was wondering if it would be possible to get the page name from the address bar using jquery or javascript. I know this can be done using PHP but don\'t really want to as
document.URL.match(/[^\/]+$/);
Just a simple alternative.
document.URL returns the document's location.
.match() is a method that filters a string using Regular Expression.
/[^\/]+$/
fetches the rest of the string starting after the last occurring slash /
.
demo
Current page: The single line sound more elegant to find the current page's file name:
location.href.split("/").slice(-1)
or
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; }
I've had an issue where i needed to remove the querystring parameters (?) and/or anchor (#) tags. I did this:
var path = window.location.pathname.toLowerCase();
// find the end of path prior the Query and Anchor designations. strip off everything after the ? or #.
// if the ? is first, then use ?, else use the #, else use the string length.
// then replace all \ with /
// then split it into an array based on /
var pagePathAry = path.substr(0, path.indexOf("?") > -1 && path.indexOf("?") < path.indexOf("#") ? path.indexOf("?") : path.indexOf("#") > -1 ? path.indexOf("#") : path.length).replace("\\", "/").split("/");
// get the folder it's in
var subFolder = pagePathAry[pagePathAry.length - 2];
// get the page name
var pageName = pagePathAry[pagePathAry.length - 1];
Try this:
var pageName = (function () {
var a = window.location.href,
b = a.lastIndexOf("/");
return a.substr(b + 1);
}());
https://developer.mozilla.org/en/DOM/window.location
alert(location.pathname)
If you don't want the leading slash, you can strip it out.
location.pathname.substring(1)
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.