Display page name in javascript?

934 Views Asked by At

How would I add location.href.split('/').pop() to a html document to display the page name? (not the whole URL) I would like to display the page name ONLY.

example: if the page was "www.example.com/whaterver/mypage.html" it would display "mypage".

What would be the full script? I am new to javascript and I found this online but I don't know the whole code. could anyone help me out?

2

There are 2 best solutions below

0
On

Note: If you do .split('.') like other solutions instruct, you will miss the base names from many URLs.


You can find the last forward slash and search ahead for the first ., ?, & or # to catch variations of URLs. This is the equivalent of PHP's basename

function getBaseName(url) {
  if(!url || (url && url.length === 0)) {
    return "";
  }
  var index = url.lastIndexOf("/") + 1;
  var filenameWithExtension = url.substr(index);
  var basename = filenameWithExtension.split(/[.?&#]+/)[0];

  // Handle '/mypage/' type paths
  if(basename.length === 0) {
    url = url.substr(0,index-1);
    basename = getBaseName(url);
  }
  return basename ? basename : ""; 
}

and use it like so

var url = "http://www.example.com/whaterver/mypage.html";
var file = getBaseName(url);

of

var file = getBaseName(location.pathname); // The current script page

Results:

http://www.example.com/whaterver/mypage/        =>  "mypage"
http://www.example.com/whaterver/mypage.html    =>  "mypage"  
http://www.example.com/whaterver/mypage         =>  "mypage"  
http://www.example.com/whaterver/mypage/        =>  "mypage"  
http://www.example.com/whaterver/mypage#works   =>  "mypage"  
http://www.example.com/whaterver/mypage?ver=1   =>  "mypage"

JSBin Demo

1
On

I would stick it in a function in case you need to reuse it elsewhere in your code. Just split the page name at the end and take the first element:

function getPageName(url) {
  return url.split('/').pop().split('.')[0];
}

You can pass in the actual URL:

var pageName = getPageName('www.example.com/whaterver/mypage.html'); // mypage

Or, using location.href:

var pageName = getPageName(location.href); // mypage

I might also be inclined to return something if there is no match for *.html, so here's a revised function that returns null if there isn't a match:

function getPageName(url) {
  var pageName = url.split('/').pop().split('.')[0];
  return pageName.length > 0 ? pageName : null;
}

DEMO