Skip to content

Website URL validation in JavaScript | Example code

  • by

With Regular expression, you can easily verify valid Website URLs in JavaScript.

Regex

string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);

Website URL validation in JavaScript

HTML example code JavaScript function to check whether a given value is a valid website URL or not. It will validate the URL with or without HTTP/HTTPS.

<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)
		};

		console.log(isValidURL("http://www.google.com"));
		console.log(isValidURL("https://www.eyehunts.com"));
		console.log(isValidURL("www.example.com"));

	</script>
</body>
</html>

Output:

Website URL validation in JavaScript

Do comment if you have any doubts or suggestions on this JS URL code.

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading