How to get base url with jquery or javascript?

后端 未结 24 1427
忘掉有多难
忘掉有多难 2020-12-12 13:59

In joomla php there I can use $this->baseurl to get the base path, but I wanted to get the base path in jquery.

The base path may be any of the follo

24条回答
  •  清歌不尽
    2020-12-12 14:57

    In case anyone would like to see this broken out into a very robust function

        function getBaseURL() {
            var loc = window.location;
            var baseURL = loc.protocol + "//" + loc.hostname;
            if (typeof loc.port !== "undefined" && loc.port !== "") baseURL += ":" + loc.port;
            // strip leading /
            var pathname = loc.pathname;
            if (pathname.length > 0 && pathname.substr(0,1) === "/") pathname = pathname.substr(1, pathname.length - 1);
            var pathParts = pathname.split("/");
            if (pathParts.length > 0) {
                for (var i = 0; i < pathParts.length; i++) {
                    if (pathParts[i] !== "") baseURL += "/" + pathParts[i];
                }
            }
            return baseURL;
        }
    

提交回复
热议问题