Remove http or https from a URL using JavaScript


Borislav Hadzhiev

Last updated: Jul 25, 2022


Photo from Unsplash

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 using 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 arguments 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.

The second argument we passed to the replace() method is the replacement for the regex match. For our purposes - 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 original 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 argument 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 doesn't start with http:// or https://, we return the string as is.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.