How can I validate a URL in JavaScript?
Gable E
gable e profile pic

To validate a URL in JavaScript, you can use regular expressions or theURL object. Here's a step-by-step guide on how to achieve this: 1. Get the URL you want to validate:

1
2
3

   const url = 'https://www.example.com';
   

Replace'https://www.example.com' with the URL you want to validate. 2. Use regular expressions: Regular expressions provide a powerful tool for pattern matching and validation. You can create a regular expression pattern that matches the desired URL format and use thetest() method to check if the URL matches the pattern.

1
2
3
4
5

   const pattern = /^https?:\/\/(?:www\.)?[a-z0-9-]+(?:\.[a-z0-9-]+)*\.[a-z]{2,}$/i;
   const isValid = pattern.test(url);
   console.log(isValid);  // Output: true
   

In this example, the regular expression pattern/^https?:\/\/(?:www\.)?[a-z0-9-]+(?:\.[a-z0-9-]+)*\.[a-z]{2,}$/i is used to match URLs starting with eitherhttp:// orhttps://, optionally followed bywww., then a domain name with one or more subdomains and a top-level domain. Thei flag makes the pattern case-insensitive. 3. Use theURL object (modern browsers): If you're working with modern browsers, you can use theURL object to validate URLs. TheURL object parses the URL and provides various properties and methods to access its components.

1
2
3
4
5
6
7
8
9
10
11

   const isValid = () => {
     try {
       new URL(url);
       return true;
     } catch (error) {
       return false;
     }
   };
   console.log(isValid());  // Output: true
   

In this example, theURL object is created with the URL string. If theURL constructor throws an error, it indicates that the URL is invalid. Choose the method that best fits your requirements and the specific context in which you need to validate a URL. Regular expressions provide flexibility and customization options, allowing you to define the specific URL format you want to validate. TheURL object, on the other hand, offers a more standardized approach with built-in URL parsing and validation functionality, but it may not be available in older browsers.