How to check if string is a URL in JavaScript
Learn, how to check if a string is URL in JavaScript with the help of examples.
To check if a string is url, we can use the following regex pattern in JavaScript.
Here is an example:
function isURL(str) {
const 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);
}
console.log(isURL("https://gmail.com"));
Output:
true
In the example above, we are passing the https://gmail.com
to the isURL() function. So, it returns true if a give url is valid otherwise it returns false.