Ali Bayat Ali Bayat - 1 year ago 77
Javascript Question

Getting last segment of url

I'm trying to extract the last segment of URLs like this:


and this:


I used below code, but this code does not work in this link:


var last_segment = window.location.hash.split('/').pop();

Answer Source

You can use the pathname, search, and/or hash part of the window.location to do this. Ignore the parser here as it is just used as an example to run this code.

var url = "http://localhost:15043/Maintenance/ModelDetails/3?blah=abc&makeId=14#test";
function parseUrl(url) {
  var a = document.createElement("a");
  a.href = url;
  return a;
var parser = parseUrl(url);
var last_segment = parser.pathname.split('/').pop();
var searchParams ="&");
var lastParamValue = searchParams[searchParams.length-1].split("=")[1];
var hash = parser.hash;