Skip to content

Facebook URL validation in JavaScript | Example code

  • by

Regular expressions are flexible enough to validate a FaceBook URL in JavaScript.

Code of Facebook URL validation in JavaScript

HTML example code.

<html>
<body>

	<script>
		
		var url1 = 'http://facebook2.com/anypage'; 

		var url2 = 'http://www.facebook.com/anypage';  
		var url3 = 'http://facebook.com/anypage';       
		var url4 = 'https://facebook.com/anypage';      
		var url5 = 'https://www.facebook.com/anypage';

		var url6 = 'facebook.com/anypage';             
		var url7 = 'www.facebook.com/anypage';         



		function validate_fb_url(url){    

			if (/^(https?:\/\/)?((w{3}\.)?)facebook.com\/.*/i.test(url))
				return 'facebook';

			return 'unknown';}

		alert('This link is ' + validate_fb_url(url2));
	</script>
</body>
</html>

Output:

Facebook URL validation in JavaScript

For Twitter and Facebook

function validate_url(url)
{
  if (/^(https?:\/\/)?((w{3}\.)?)twitter\.com\/(#!\/)?[a-z0-9_]+$/i.test(url))
     return 'twitter';    

 if (/^(https?:\/\/)?((w{3}\.)?)facebook.com\/.*/i.test(url))
     return 'facebook';

 return 'unknown';
}

Do comment if you have any doubts and suggestion 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