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

前端 未结 6 721
生来不讨喜
生来不讨喜 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: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);
    

提交回复
热议问题