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

前端 未结 6 677
生来不讨喜
生来不讨喜 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: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://.

提交回复
热议问题