ArrowLeft Icon

Valid HTTP URL

๐Ÿ“† ยท ๐Ÿ‘€
export const isValidHTTPUrl = (string) => {
let url;
try {
url = new URL(string);
} catch {
return false;
}
return ['http:', 'https:'].includes(url.protocol);
};

We are using the URL โ†—๏ธ API to check if a passed string is valid or not.

The first try/catch will immediately catch if the string is a valid URL or not, if it is not, it will throw an error like Uncaught TypeError: URL constructor: string is not a valid URL. In such a case, we would return false in the catch block

In case itโ€™s a valid URL, the last line checks if itโ€™s a valid HTTP/HTTPS URL.

Note: This method has no false negatives (as far as I know) but does have some false positives

Some examples of false positives could be http://.. or http:/a which are considered valid URLs, even though the DNS might not resolve for these URLs, you can read the RFC 3986 โ†—๏ธ for more details.

Nevertheless, I would prefer to use this over the complex Regex which could potentially break the internet โ†—๏ธ