Get relative URL from absolute URL

后端 未结 8 1903
自闭症患者
自闭症患者 2020-12-03 04:42

I want to get the relative URL from an absolute URL in JavaScript using regex and the replace method.

I tried the following but it is not working:

va         


        
8条回答
  •  伪装坚强ぢ
    2020-12-03 05:30

    A nice way to do this is to use the browser's native link-parsing capabilities, using an a element:

    function getUrlParts(url) {
        var a = document.createElement('a');
        a.href = url;
    
        return {
            href: a.href,
            host: a.host,
            hostname: a.hostname,
            port: a.port,
            pathname: a.pathname,
            protocol: a.protocol,
            hash: a.hash,
            search: a.search
        };
    }
    

    You can then access the pathname with getUrlParts(yourUrl).pathname.

    The properties are the same as for the location object.

提交回复
热议问题