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.

  1. protocol
  2. Domain name address
  3. IP (v4) address
  4. port and path
  5. URL query string
  6. 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.com/')); // 👉️ true
console.log(isValidURL('httpe://infinitbility.com/')); // 👉️ false

if (isValidURL('http://www.infinitbility.com/')) {
  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.

javascript, check if a string is a valid url example
javascript, check if a string is a valid url example

I hope it’s help you, All the best 👍.