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
.
You can use the URLConstructor to check if a string is a valid URL. URLConstructor ( new URL(url) ) returns a newly created URL object defined by the URL parameters. A JavaScript TypeError exception is thrown if the given URL is not valid.
Use indexOf() to Check if URL Contains a String When a URL contains a string, you can check for the string's existence using the indexOf method from String. prototype. indexOf() . Therefore, the argument of indexOf should be your search string.
A query string is a part of a uniform resource locator (URL) that assigns values to specified parameters.
A URL is a valid URL if at least one of the following conditions holds: The URL is a valid URI reference [RFC3986]. The URL is a valid IRI reference and it has no query component. [RFC3987]
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 aboveA related question with an answer
Or this Regexp from Devshed:
function validURL(str) { var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string '(\\#[-a-z\\d_]*)?$','i'); // fragment locator return !!pattern.test(str); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With