w3resource

JavaScript: Check whether a given value is an valid url or not

JavaScript validation with regular expression: Exercise-9 with Solution

Validate URL

Write a JavaScript function to check whether a given value is a valid URL or not.

Sample Solution:

JavaScript Code:

function is_url(str)
{
  regexp =  /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
        if (regexp.test(str))
        {
          return true;
        }
        else
        {
          return false;
        }
}

console.log(is_url("http://www.example.com"));
console.log(is_url("https://www.example.com"));
console.log(is_url("www.example.com"));

Output:

true
true
true

Flowchart:

Flowchart: JavaScript- Check whether a given value is an valid url or not

Live Demo:

See the Pen javascript-regexp-exercise-8 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that uses a regular expression to validate a URL according to common standards.
  • Write a JavaScript function that parses a URL and checks if it contains a valid protocol and domain.
  • Write a JavaScript function that validates a URL and returns a boolean, handling both http and https.
  • Write a JavaScript function that trims the input and tests it against a regex to ensure it’s a properly formatted URL.

Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript function to count the number of vowels in a given string.
Next: Write a JavaScript function to check whether a given value is alpha numeric or not.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.