How to get the directory part of current URL in JavaScript?

console.log(new URL(document.URL));

you would get all object like this :

{
  href:"https://yy.xx.id/index.php/5351/user/private/images%20%282%29.jpeg?forcedownload=1",

  origin:"https://smi.kerjaindonesia.id", 
  protocol: "https:", 
  username: "", 
  password: "", 
  pathname: "index.php/5351/user/private/images%20%282%29.jpeg"  ,
  port: "" ,
  protocol: "https:",
  search: "?forcedownload=1"
}

Try this document.URL.substr(0,document.URL.lastIndexOf('/'))

It will work for sure!


This one-liner also works:

document.URL.split('/').slice(0, -1).join('/')

/* to avoid query parameters, use pathname instead of href */
var l = document.location.pathname.split('/');
l.pop();
console.log(document.location.origin + l.join('/'));