javascriptwindow.location

Cut protocol, host and port from window.location.href


Is there a way to cut protocol, host and port from window.location.href?

Right now I have only this option.

const windowUrlPattern = () => {
  let windowUrl;
  if (window.location.search.length !== 0 && window.location.hash.length === 0) {
    windowUrl = `${window.location.pathname}/${window.location.search}`;
  } else if (window.location.search.length !== 0 && window.location.hash.length !== 0) {
    windowUrl = `${window.location.pathname}/${window.location.search}${window.location.hash}`;
  } else {
    windowUrl = window.location.pathname;
  }
  return windowUrl;
}

console.log(windowUrlPattern());

is there a way to make it cleaner or more certain, just to cut window.location.protocol, window.location.host and window.location.port out of href?

thank you.


Solution

  • You mean

    const windowUrlPattern = href => {
      const url = new URL(href);
      return [url.pathname,url.search,url.hash].join("")
    }
    
    console.log(windowUrlPattern(location.href));
    console.log(windowUrlPattern("https://www.example.com/folder/page.html"));
    console.log(windowUrlPattern("https://www.google.com/search?q=test"));
    console.log(windowUrlPattern("https://www.google.com/search?q=test#page2"));