Clue Mediator

Remove hostname and port from URL using JavaScript

📅August 2, 2022

In this short article, we’ll show you how to remove hostname and port from URL using JavaScript. There are numerous possible techniques, but we'll focus on two of them.

Different methods to remove hostname and port from URL

  1. Using Regular Expression
  2. Using URL API

1. Using Regular Expression

Let’s use the regular expression to remove the hostname and port from the URL.

var URL = "http://localhost:4000/url-path-name";
var newURL = URL.replace(/^[a-z]{4,5}\:\/{2}[a-z]{1,}\:[0-9]{1,4}.(.*)/, '$1');
console.log(newURL); // Output: url-path-name

2. Using URL API

Here, we will use the URL API to remove the hostname and port from URL.

var urlObj = new URL("http://localhost:4000/url-path-name");
var newURL = urlObj.href.replace(urlObj.origin, '');
console.log(newURL); // Output: /url-path-name

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂