Last updated: Mar 4, 2024
Reading timeยท3 min
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?:\/\//, ''); } // ๐๏ธ "bobbyhadz.com" console.log(removeHttp('https://bobbyhadz.com')); // ๐๏ธ "bobbyhadz.com" console.log(removeHttp('http://bobbyhadz.com'));
We created a reusable function that removes the http://
or https://
part of
the given URL.
The String.replace() method returns a new string with one, some, or all matches of a regular expression replaced with the provided replacement.
The method takes the following parameters:
Name | Description |
---|---|
pattern | The pattern to look for in the string. Can be a string or a regular expression. |
replacement | A string used to replace the substring match by the supplied pattern. |
/ /
mark the beginning and end of the regular expression.function removeHttp(url) { return url.replace(/^https?:\/\//, ''); }
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.
The second argument we passed to the replace()
method is the replacement for
the regex match.
We used an empty string because we wanted to remove the http://
part.
If you ever need help reading a regular expression, check out this regular expression cheat sheet by MDN.
It contains a table with the name and the meaning of each special character with examples.
If you want to avoid using regular expressions, use the String.startsWith
method instead.
This is a two-step process:
https://
or http://
.slice()
method to get the part of the URL after the
http
protocol.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; } // ๐๏ธ "bobbyhadz.com/books" console.log(removeHttp('https://bobbyhadz.com/books')); // ๐๏ธ "bobbyhadz.com" console.log(removeHttp('http://bobbyhadz.com'));
We first check if the URL starts with https://
.
If it does, we use the String.slice() method to get the part 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.
// ๐๏ธ "example.com" console.log('http://bobbyhadz.com'.slice(7));
We used the length of the http://
or https://
strings to determine the start
index, just so we can avoid hardcoding a magic number.
If the URL doesn't start with http://
or https://
, we return the string as
is.
You can learn more about the related topics by checking out the following tutorials: