Remove http or https from a URL using JavaScript


Borislav Hadzhiev

Fri Nov 19 20212 min read


Photo by Matt Popovich

Remove 'http://' or 'https://' from a URL #

To remove http:// or https:// from a url, call the replace() method with the following regular expression - /^https?:\/\// and an empty string as parameters. The replace method will return a new string, where the http:// part is removed.

function removeHttp(url) { return url.replace(/^https?:\/\//, ''); } // 👇️ "" console.log(removeHttp('')); // 👇️ "" console.log(removeHttp(''));
If you're looking to avoid regular expressions, scroll down to the next subheading.

We created a reusable function that removes the http:// or https:// part of a url.

We passed the following 2 parameters to the String.replace method:

  1. a regular expression we want to match in the string
  2. the replacement for each match

The forward slashes / / mark the beginning and end of the regular expression.

The caret ^ matches the beginning of the input, in other words, the string has to start the http(s).

The question mark ? matches the preceding item 0 or 1 times. In the example the question mark makes the s character optional.

Lastly, we have to escape the forward slashes using backslashes.

If you ever need help reading a regular expression, check out this regex cheatsheet from MDN. It's by far the best one out there.

The second parameter we passed to the replace() method is the replacement for the regex match. In our case - an empty string because we want to remove the http:// part.

If you want to avoid using regular expressions, use the String.startsWith method instead.

Remove 'http://' or 'https://' from a URL using startsWith #

To remove http:// or https:// from a url, check if the url starts with https:// or http:// and if it does, use the slice() method to get the part of the url after the http protocol. The slice method returns a new string that represents a portion of the origin string.

function removeHttp(url) { if (url.startsWith('https://')) { const https = 'https://'; return url.slice(https.length); } if (url.startsWith('http://')) { const http = 'http://'; return url.slice(http.length); } return url; } // 👇️ "" console.log(removeHttp('')); // 👇️ "" console.log(removeHttp(''));

We first check if the url starts with https://, if it does we use the String.slice method to get the piece of the url after the protocol.

The only parameter we passed to the slice method is the start index - the index of the first character to be included in the string.

// 👇️ "" console.log(''.slice(7));

We used the length of the http:// or https:// strings to determine the start index, just so we can avoid hard coding a magic number.

If the url does not start with http:// or https:// we return the string as is.

Use the search field on my Home Page to filter through my more than 1,000 articles.