Skip to content

URL validation regex JavaScript | Example code

  • by

URL is valid or Invalid can check the RegExp in match method in JavaScript.

URL validator JavaScript

function validURL(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);
}

URL validation regex JavaScript Example

HTML example code: – Check if a JavaScript string is a URL

A validate URL with or without http No matter what function return true and false based on structure of URL.

<html>
<body>

	<script>
		function isValidURL(string) {
			var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
			return (res !== null)
		};

		var testCase1 = "http://eyehunts.com";

		alert(isValidURL(testCase1)); 
	</script>

</body>
</html>

Output:

URL validation regex JavaScript

Do comment if you have any suggestions or doubts in this JS URL topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *