Skip to content

URL regex validation JavaScript | Example code

  • by

URL regex validation is the best way to check if a string is a valid URL or not. Just pass the Regex in the match method to validate the URL.

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

URL regex validation Example

HTML Example code check if an URL is valid or not using Regular Expression:-

<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 tc1 = "http://en.wikipedia.org/wiki/Procter_&_Gamble";
    console.log(isValidURL(tc1)); 

    var tc2 = "http://www.google.com/url?sa=i&rct=j&q=&";
    console.log(isValidURL(tc2)); 

    var tc3 = "https://sdfasd";
    console.log(isValidURL(tc3)); 

    var tc4 = "dfdsfdsfdfdsfsdfs";
    console.log(isValidURL(tc4)); 

    var tc5 = "magnet:?xt=urn:btih:123";
    console.log(isValidURL(tc5)); 

    var tc6 = "https://eyehunts.com/";
    console.log(isValidURL(tc6)); 

    var tc7 = "https://w";
    console.log(isValidURL(tc7)); 

    var tc8 = "https://sdfasdp.ppppppppppp";
    console.log(isValidURL(tc8)); 
</script>

Output:

URL regex validation JavaScript
  • The URL starts with either HTTP or HTTPS and
  • then followed by :// and
  • then it must contain www. and
  • then followed by a subdomain of length (2, 256) and
  • The last part contains the domain.

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

Discover more from Tutorial

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

Continue reading