JavaScript: Check whether a given value is an valid url or not
JavaScript validation with regular expression: Exercise-9 with Solution
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:
Live Demo:
See the Pen javascript-regexp-exercise-8 by w3resource (@w3resource) on CodePen.
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/javascript-exercises/javascript-regexp-exercise-9.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics