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

前端 未结 6 675
生来不讨喜
生来不讨喜 2021-01-11 12:42

I\'m trying to add a \"back to dir\" button at the top of a web page, which would redirect the user to the same URL, but with no filename in it.

For example, clickin

相关标签:
6条回答
  • 2021-01-11 13:14

    This one-liner also works:

    document.URL.split('/').slice(0, -1).join('/')
    
    0 讨论(0)
  • 2021-01-11 13:19

    The following gets directories, including the case where the last character is a slash.

    document.URL.replace(/\/[^/]+\/?$/, '');
    

    This effectively states the following (assuming they can be found in this order)

    1. \/: Find a "/"
    2. [^/]+: Find one or more characters after it that are not "/"
    3. \/?: Find an optional "/" after those character(s)
    4. $: Find the end of the string

    Then remove these by '', so we're left with the directory only.

    Again, this assumes there is a slash present marking a directory and that this is not just a URL where the only slashes are within http://.

    0 讨论(0)
  • 2021-01-11 13:20
    /* to avoid query parameters, use pathname instead of href */
    var l = document.location.pathname.split('/');
    l.pop();
    console.log(document.location.origin + l.join('/'));
    
    0 讨论(0)
  • 2021-01-11 13:25

    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"
    }
    
    0 讨论(0)
  • 2021-01-11 13:33

    Try the following, which takes into account both when the URL ends in a trailing slash and when it doesn't:

    var currUrl = document.URL,
        newUrl;
    if (currUrl.charAt(currUrl.length - 1) === '/') {
        newUrl = currUrl.slice(0, currUrl.lastIndexOf('/'));
        newUrl = newUrl.slice(0, newUrl.lastIndexOf('/')) + '/';
    } else {
        newUrl = currUrl.slice(0, currUrl.lastIndexOf('/')) + '/';
    }
    console.log(newUrl);
    
    0 讨论(0)
  • 2021-01-11 13:38

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

    It will work for sure!

    0 讨论(0)
提交回复
热议问题