如何在纯html前端中,如何使用js或者jQuery动态获取项目路径

在百度上搜索,发现都是相互抄袭,是下面我贴出来的这种截取的,但是我运行发现, 如果项目路径是/那么就会出错

<body>
获取当前网址:<h1 id="curWwwPath"></h1>
获取主机地址之后的目录:<h1 id="pathName"></h1>
获取主机地址:<h1 id="localhostPaht"></h1>
获取带"/"的项目名: <h1 id="projectName"></h1>


<script>


   window.onload =  function getRootPath() {
        var curWwwPath = window.document.location.href;
        var pathName = window.document.location.pathname;
        var pos = curWwwPath.indexOf(pathName);
        var localhostPaht = curWwwPath.substring(0, pos);
        var projectName = pathName.substring(0, pathName.substr(1).indexOf('/')+1 );
        document.getElementById("curWwwPath").innerHTML=curWwwPath;
        document.getElementById("pathName").innerHTML=pathName;
        document.getElementById("localhostPaht").innerHTML=localhostPaht;
        document.getElementById("projectName").innerHTML=projectName;
    }
</script>
</body>

所以我想请教下前端大佬,如何使用js动态获取项目路径,即使项目路径是/的情况.

回复
阅读 3.2k
3 个回答

不知道你想干啥,?‍♀️

但是你可以通过判断做不一样的处理,比如当路径是 / 的时候

if(location.pathname == '/') {
    var projectName = '/';
} else {
    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/')+1 );
}

我自己在用的

    let uri = Object.create(null, {});
    (function(){

        let dom = document.createElement('A');
        function getAbsoluteUri($uri, $trimEndSlash)
        {
            dom.href = $uri;

            $uri = dom.href;

            if($trimEndSlash !== true)
                return $uri;

            let match = /^(.*?)(\/+)?$/.exec($uri);

            return match[1];
        }

        let uriThis = getAbsoluteUri('', true);

        this.root = getAbsoluteUri('/', true);
        this.base = getAbsoluteUri('..', true);
        this.page = getAbsoluteUri('.', true);

        this.full = uriThis.substr(0, (uriThis+'?').indexOf('?'));
        this.path = this.full.replace(this.base, '');
        this.file = this.full.substr(this.full.lastIndexOf('/') + 1);

        console.log(this);
    }).call(uri);

使用是否包含来判断吧

href.includes("192.168.1.166:8055")
推荐问题
宣传栏