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:";
}
I change the function to Match + make a change here with the slashes and its work: (http:// and https) both
function isValidUrl(userInput) {
var res = userInput.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
if(res == null)
return false;
else
return true;
}
function isURL(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);
}
Improvement on the accepted answer...
Allows @ symbol in path e.g. https://medium.com/@techytimo
isURL(str) {
var pattern = new RegExp('^((ft|htt)ps?:\\/\\/)?'+ // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name and extension
'((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
'(\\:\\d+)?'+ // port
'(\\/[-a-z\\d%@_.~+&:]*)*'+ // path
'(\\?[;&a-z\\d%@_.,~+&:=-]*)?'+ // query string
'(\\#[-a-z\\d_]*)?$','i'); // fragment locator
return pattern.test(str);
}
You can use the URL native API:
const isUrl = string => {
try { return Boolean(new URL(string)); }
catch(e){ return false; }
}
If you can change the input type, I think this solution would be much easier:
You can simple use type="url"
in your input and the check it with checkValidity()
in js
E.g:
your.html
<input id="foo" type="url">
your.js
// The selector is JQuery, but the function is plain JS
$("#foo").on("keyup", function() {
if (this.checkValidity()) {
// The url is valid
} else {
// The url is invalid
}
});