Get relative URL from absolute URL

Below snippet returns the absolute URL of the page.

 var myURL = window.location.protocol + "//" + window.location.host  + window.location.pathname;

If you need only the relative url just use below snippet

 var myURL=window.location.pathname;

Checkout get relative URL using Javascript for more details and multiple ways to achieve the same functionality.


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.