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 s
You can try to use URL constructor: if it doesn't throw, the string is a valid URL:
function isValidUrl(string) {
try {
new URL(string);
} catch (_) {
return false;
}
return true;
}
The term 'URL' is defined in RFC 3886 (as URI); it must begin with a scheme name, and the scheme name is not limited to http/https.
Notable examples:
www.google.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 DNShttps://google..com
is valid URL, same as aboveIf you want to check whether a string is a valid HTTP URL:
function isValidHttpUrl(string) {
let url;
try {
url = new URL(string);
} catch (_) {
return false;
}
return url.protocol === "http:" || url.protocol === "https:";
}