A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/how-to-validate-url-using-regular-expression-in-javascript/ below:

JavaScript - Validate URL in JS

JavaScript - Validate URL in JS

Last Updated : 11 Jul, 2025

We will explore different approaches to validating URLs in JavaScript. These approaches include using regular expressions (regex), the URL constructor, and various npm packages. let's see one by one.

All valid URLs follow a particular pattern. They have three main parts, which are:

1. Using Regular Expression

To validate a URL in JavaScript using a regular expression (regex), we will use the following pattern to match the common URL format in the below example.

JavaScript
function isValid(url) {
    const pattern = /^(https?:\/\/)?([\w-]+\.)+[\w-]+(\/[\w-]*)*$/;
    return pattern.test(url);
}

//Driver Code Starts
console.log(isValid("https://www.example.com////"));
console.log(isValid("http://example.com////"));  
console.log(isValid("www.example.com"));   
console.log(isValid("invalid-url"));     
//Driver Code Ends

Output
true
true
true
false
Explanation of the Regular Expression we used: 2. Using URL Object

The URL object in JavaScript provides a built-in way to parse and validate URLs. It is robust, handles complex cases, and doesn't require writing or maintaining custom regular expressions.

JavaScript
function isValid(url) {
    try {
        new URL(url);
        return true;
    } catch (e) {
        return false;
    }
}


//Driver Code Starts
console.log(isValid("https://www.example.com////")); 
console.log(isValid("http://example.com////"));     
console.log(isValid("www.example.com"));      
console.log(isValid("invalid-url"));         
//Driver Code Ends

Output
true
true
false
false
3. Using npm Packages

There are two npm packages is-url and is-url-http to validate URL. Install the packages with the following command:

npm install is-url
npm install is-url-http
Using is-url npm Packages JavaScript
import isUrl from 'is-url';
console.log(isUrl("https://www.example.com////")); 
console.log(isUrl("http://example.com////"));   
console.log(isUrl("www.example.com"));       
console.log(isUrl("invalid-url"));           

Output

true
true
false
false
4. Using is-url-http npm Packages JavaScript
import isUrlHttp from 'is-url-http';
console.log(isUrlHttp("https://www.example.com////"));
console.log(isUrlHttp("http://example.com////"));   
console.log(isUrlHttp("www.example.com"));     
console.log(isUrlHttp("invalid-url")); 			 

Output

true
true
false
false


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4