Hi Friends 👋,
Welcome To Infinitbility! ❤️
Today, I’m going to show you, how do you check if a string is a valid URL in javascript, here I will use the regex expression to validate URL string.
To validate the string URL, I will use the below regex which can handle the below cases.
- protocol
- Domain name address
- IP (v4) address
- port and path
- URL query string
- fragment locator
function isValidURL(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);
}
Let’s start the today’s tutorial title How do I check if a string is a valid URL in javascript?
Here, we will use the above-mentioned function isValidURL()
to check if the string URL is valid or not, to use the above function we just pass out the URL in an isValidURL()
method and it will return true
or false
based on valid ur string.
Let’s understand with an example.
function isValidURL(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);
}
console.log(isValidURL('http://infinitbility.github.io/')); // 👉️ true
console.log(isValidURL('httpe://infinitbility.github.io/')); // 👉️ false
if (isValidURL('http://www.infinitbility.github.io/')) {
console.log('✅ Valid URL')
} else {
console.log('⛔️ Invalid URL')
}
When running the above program it should log which URL address is valid and which is not. let’s check the output.
I hope it’s help you, All the best 👍.