Is there a way in JavaScript to check if a string is a URL?
RegExes are excluded because the URL is most likely written like stackoverflow
; that is to say that it might not have a .com
, www
or http
.
Is there a way in JavaScript to check if a string is a URL?
RegExes are excluded because the URL is most likely written like stackoverflow
; that is to say that it might not have a .com
, www
or http
.
If you want to check whether a string is valid HTTP URL, you can use URL
constructor (it will throw on malformed string):
function isValidHttpUrl(string) {
let url;
try {
url = new URL(string);
} catch (_) {
return false;
}
return url.protocol === "http:" || url.protocol === "https:";
}
Note: Per RFC 3886, URL must begin with a scheme (not limited to http/https), e. g.:
www.example.com
is not valid URL (missing scheme)javascript:void(0)
is valid URL, although not an HTTP onehttp://..
is valid URL with the host being ..
(whether it resolves depends on your DNS)https://example..com
is valid URL, same as above