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
.
Improvement on the accepted answer...
Allows @ symbol in path e.g. https://medium.com/@techytimo
Here is yet another method.
(I don't have reps to comment on ValidURL example; hence post this as an answer.)
While use of protocol relative URLs is not encouraged (The Protocol-relative URL), they do get employed sometimes. To validate such an URL with a regular expression the protocol part could be optional, e.g.:
As others noted, regular expression does not seem to be the best suited approach for validating URLs, though.
I can't comment on the post that is the closest #5717133, but below is the way I figured out how to get @tom-gullen regex working.
To Validate Url using javascript is shown below
This seems to be one of the hardest problems in CS ;)
Here's another incomplete solution that works well enough for me and better than the others I've seen here. I'm using a input[type=url] for this in order to support IE11, otherwise it would be much simpler using window.URL to perform the validation instead:
In order to accept incomplete inputs such as "www.mydomain.com" it will also make it valid assuming the protocol is "http" in those cases and returning the valid URL if the address is valid. It returns false when invalid.
It also supports IPv4 domains, but not IPv6.