How to validate URL address in JavaScript?

JavascriptWeb DevelopmentFront End Technology

To validate URL address in JavaScript, use “regex” as in the following code. It returns “true” for correct URL address, else “false”

Example

Live Demo

<!DOCTYPE html>
<html>
   <body>
      <script>
         var myURL;
         function validURL(myURL) {
            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}))'+ // ip (v4) address
            '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ //port
            '(\\?[;&amp;a-z\\d%_.~+=-]*)?'+ // query string
            '(\\#[-a-z\\d_]*)?$','i');
            return pattern.test(myURL);
         }
         document.write(validURL("http://qries.com"));
      </script>
   </body>
</html>
raja
Published on 30-Jan-2018 10:33:32
Advertisements