Ali Bayat Ali Bayat - 3 months ago 5
Javascript Question

Getting last segment of url

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

localhost:15043/Maintenance/ModelDetails/3?makeId=14


and this:

//localhost:15043/Maintenance/ModelDetails/3


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

localhost:15043/Maintenance/ModelDetails/3?makeId=14

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

Answer

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 = parser.search.substring(1).split("&");
var lastParamValue = searchParams[searchParams.length-1].split("=")[1];
var hash = parser.hash;

console.log(last_segment);
console.log(lastParamValue);
console.log(hash);